0

I imported a csv file containing zip codes as a string using the following line:

my_data = genfromtext('path\to\file.csv', delimiter = ',', dtype=str, autostrip=True)

I am importing as a string in order to keep the leading zeroes some zip codes may contain. Now I need to also loop through the entire numpy array and I wanted to do so like this:

for i in np.nditer(my_data): 
     do something with my_data[i]

But unfortunately it is returning the following error:

Arrays used as indices must be of integer (or boolean) type

Any idea how I can loop through each element of this numpy array?

2 Answers 2

1

While looping over NumPy arrays is often not a good solution, you can do it like this:

for i in range(len(my_data)): 
     do something with my_data[i]

You might be better off reading your data into a list, process the strings, and convert into NumPy array afterwards.

Sign up to request clarification or add additional context in comments.

3 Comments

This actually worked! Although it looks like its pretty slow, processing about 3 zips per second. Would you happen to know a faster way by any chance?
In NumPy you want whole-array operations. It depends very much the do something actually does if you can do it without loops.
Thanks I will definitely look more into it
1

You should do something with i, not with my_data[i]. i is already your element (a part if mydata). Thats why my_data[i] is not working, becouse i is not an index. it is a numpy array.

If you want to use index, and the given element too, use enumerate()

Example:

lista = [20,50,70]
for idx, element in  enumerate(lista): 
    print (idx, element)

For more info visit this site numpy iteration tutorial

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.