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: 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()
Sign up to request clarification or add additional context in comments.

3 Comments

More performant version: (age_new.values > 100).astype(int).tolist()
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()
almost! use the bit-wise and operator & instead of &&. && is not a valid python operator. Similarly, the bit-wise or operator is | and not ||
1

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

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

Comments

0

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

for v in dct.values:
    if v <= 100:
        ...

3 Comments

that outputs KeyError: 218
what if you do: if i <= 100 ?
values is not a function of a pandas Series. This is not a dictionary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.