How to Read Vector File and Write Only Indexes with Criteria

I wrote a code that reads a file containing a list of vectors and writes in another file the indexes + 1 of the values that contain Zeros.

Example:

input.csv
0,0,1,0,1
1,1,1,0,0
0,1,0,1,0
1,0,1,0,1
0,0,1,1,0

result.csv:
1,2,4
4,5
1,3,5
2,4
1,2,5

Below is the code, but it is giving error:

import numpy as np

with open("c:\input.csv","r") as csv_file, open("c:\result.csv","w") as output:
    for line in csv_file:
        x = np.array(line)
        output.write(np.flatnonzero(x==0)+1) 


Result => AttributeError: ‘bool’ object has no attribute ‘ravel’

However, when I write the code without using a vector list in a file, the code works normally. See below:

import numpy as np

x = np.array([0,0,1,0,1]) 
print(np.flatnonzero(x==0)+1) # Index + 1 -> contain Zeros


Result: [1 2 4]

What am I doing wrong in the first code?

Answer

What you’re reading is a string, “0,0,1,0,1n”. numpy does not know how to translate that. It created an array of 5 string objects. Try this.

  for line in csv_file:
    x = np.array(list(int(k) for k in line.strip().split(',')))

Leave a Reply

Your email address will not be published. Required fields are marked *