Search code examples
pythonnumpytxt

How to skip a row of zeros with np.loadtxt?


I have a .txt file that contains many rows of numeric values. Each row looks as follows 3.896784 0.465921 1.183185 5.468042 ..., where the values differ depending on the row.

Furthermore, every row contains 900 values. Some rows do not contain real data, but only 900 zeros as follows 0 0 0 0 0 0 0 0 ....

I know how to skip rows that only contain one value, i.e., one zero, such as via the following code:

import numpy as np

data = np.loadtxt("pathtodata")
data = data[~(data==0)]

But this code does not work for 2 zero values or more per row. Is there a way to not load rows that only contain 900 or any arbitrary number of zeros (or a specific integer)?


Solution

  • import numpy as np
    
    data = np.loadtxt("data.txt")
    data = data[~np.all(data == 0, axis=1)]
    
    
    for row in data:
        print(row)
    

    Should do the trick, np.all(data == 0, axis=1) is essentially what you are asking for, it checks if every element in a given row verify a condition, here you exclude every row where every element are equal to 0