2

I am trying to create a for loop that iterates through a pandas Series, ageNew, that fills a list, label , based on the contents of the pandas Series.

This is the code that I have which outputs errors:

In:

for i in ageNew.items():
    if ageNew[i] <= 100:
        val = 0
    else:
        val = 1
    label.append(val)

Out:

KeyError: (0, 218)
2
  • for k,v in age_new.items() don't use camalCase Commented May 22, 2018 at 15:31
  • 3
    You can use .values instead of .items(): for i in ageNew.values:
    – pault
    Commented May 22, 2018 at 15:33

3 Answers 3

5

use vector operations instead of loops for efficiency and brevity

label = (age_new > 100).astype(int).tolist()
3
  • 2
    More performant version: (age_new.values > 100).astype(int).tolist()
    – jpp
    Commented May 22, 2018 at 15:37
  • oh that is cool, just out of curiosity, how would a vector operation work for a non-binary value, i.e. label can equal 0,1, or 2. Would it be like this: ((age_new <= 42) && (age_new > 7)).astype(int).tolist()
    – cool_beans
    Commented May 22, 2018 at 15:49
  • 1
    almost! use the bit-wise and operator & instead of &&. && is not a valid python operator. Similarly, the bit-wise or operator is | and not || Commented May 22, 2018 at 16:01
1

when you use item() you need to pass two arguments in for statment example:

for k,v in dct.items():
    print(k, v)
0

You can use .values instead of .items() to get just the value:

for v in dct.values:
    if v <= 100:
        ...
3
  • that outputs KeyError: 218
    – cool_beans
    Commented May 22, 2018 at 15:41
  • what if you do: if i <= 100 ? Commented May 22, 2018 at 15:43
  • 1
    values is not a function of a pandas Series. This is not a dictionary.
    – pault
    Commented May 22, 2018 at 15:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.