Home > database >  How to iterate list in numpy and avoid TypeError: Only integer scalar arrays can be converted to a s
How to iterate list in numpy and avoid TypeError: Only integer scalar arrays can be converted to a s

Time:11-30

I am using numpy: I have a list:[array([2, 5, 0, 6, 6, 0, 2, 0]), array([3, 2, 5, 4, 4, 5, 6, 0]), array([1, 1, 5, 1, 4, 6, 0, 0]), array([1, 3, 5, 4, 2, 2, 5, 3]), array([5, 0, 6, 3, 1, 0, 5, 3]), array([1, 5, 1, 6, 0, 3, 5, 5]), array([4, 6, 1, 1, 3, 5, 2, 6]), array([5, 5, 1, 2, 6, 0, 5, 0])] <class 'list'>

I want to be able to iterate each array in the list and pass it through a function and make a new list of outcomes for that I have this:

fit=[]
for i in collection:
    state = collection[i]
    test = Review(state)
    fit.append(test.function())
print(fit) 

But I get the following type error:

TypeError: only integer scalar arrays can be converted to a scalar index

i needs to be an int but in this case, it would be an array from the list and what I need to do is pass each array to this function to get a result and add this to the new fit list

CodePudding user response:

The for loop iterates over collection and as such i will be an element of collection. You're getting the error because i is not an int. Also the line state = collection[i] is redundant. Instead you can simply do state = i

After your comment, if you would like to iterate over the inner arrays you will need a second loop. To take your example of summing the arrays it would look something like this:

for i in collection:
    arr_sum = 0
    for j in i:
        arr_sum  = j
    print(f'Array sum is {arr_sum}')

Note that for the application of a simple sum you can use the sum() function.

CodePudding user response:

To iterate over list of arrays, try this:

fit=[]
for state in collection: #Iterate over each element in the collection
    test = Review(state)
    fit.append(test.function())
print(fit) 

Or

fit=[]
for i in collection:
    state = i
    test = Review(state)
    fit.append(test.function())
print(fit) 
  • Related