Luck
Luck

Reputation: 23

Why do I get 'TypeError: 'numpy.int64' object is not iterable' when trying to iterate over a list?

I'm trying to compare 2 items in a list that work as the values in a dictionary, but it keeps getting converted to numpy.int64 and I don't understand why.

I've tested for 'valores' type using only the first loop and the second one. In the first I get a a list, but in the second I get numpy.int64.

import pandas as pd 
import pprint
.
.
.
questionario = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}

for variavel, valores in questionario.items():
  for q_passado, q_atual in valores:
    if q_passado and q_atual != 0:
      if q_atual / q_passado > 0.5:
        print(variavel, q_passado, q_atual)

I expected the output to be something like 'a 1 2', etc.

Upvotes: 2

Views: 17141

Answers (3)

VietHTran
VietHTran

Reputation: 2318

You don't need a for loop for valores (for q_passado, q_atual in valores) since it is a list of 2 elements that can be accessed by expression valores[0] and valores[1]. You can fix it by simply change to:

import pandas as pd 
import pprint
questionario = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}

for variavel, valores in questionario.items():
    if valores[0] and valores[1]!= 0:
        if valores[1] / valores[0] > 0.5:
            print(variavel, valores[0], valores[1])

Upvotes: 1

jose_bacoy
jose_bacoy

Reputation: 12684

You cannot assign the variables to the list. Instead, assign the variables one by one.

 OLD: for q_passado, q_atual in valores:
 NEW: q_passado, q_atual = valores[0], valores[1]

 Result:
     a 1 2
     b 3 4
     c 5 6

Upvotes: 0

razdi
razdi

Reputation: 1440

You've made a mistake while writing the != 0 conditions. You need to seperate these conditions out otherwise the operator precedence messes the logic.

You can use comprehension to trim it down to a one lines:

questionario = {'a': [1, 2], 'b': [3, 4], 'c': [5, 6], 'd' :[1, 0], 'e': [14,6]}

output = ["{} {} {}".format(k, v[0], v[1]) for k,v in questionario.items() if v[0] != 0 and v[1] != 0 and v[1]/v[0] > 0.5]

And the output is:

['a 1 2', 'c 5 6', 'b 3 4']

Explanation:

for k,v in questionario.items()

This extracts the key value pairs from your dictionary

if v[0] != 0 and v[1] != 0 and v[1]/v[0] > 0.5

This bundles up the conditions you wrote inside the loop.

As a result, k,v will only contain values that satisfies these conditions.

Finally, this adds the values to a string and wraps them in a list:

"{} {} {}".format(k, v[0], v[1])

Upvotes: 0

Related Questions