0

One more question on Pandas. I have a dataframe called df, one column of which is called age_year and contains ages of different people from 20 to 70 years old. I need to group all those ages into 4 groups and visualize later basing on another criteria all those people have in a dataframe. However when i write a function and then try to pipe() it for my groupby method, it throws "Truth value" error.

def age_group(series):
    if df["age_year"] < 40:
        df["age_young"] = df["age_year"]
    elif df["age_year"] > 40 & df["age_year"] < 50:
        df["age_40"] = df["age_year"]
    elif df["age_year"] > 50 & df["age_year"] < 60:
        df["age_50"] = df["age_year"]
    else:
        df["age_60"] = df["age_year"]

df.groupby('age_year').pipe(age_group("age_year"))
ela rednax
  • 53
  • 1
  • 8
  • A series has more than one value, so when using an if statement it is ambiguous because, part of the series is True and other parrs are False. So you need to us `any` or `all`. – Scott Boston Mar 27 '21 at 17:03
  • you have a logic error ... 40 and 50 will drop through to `else` – jsotola Mar 27 '21 at 17:08
  • it is simpler to reverse the `if .. elif` blocks .... like this `if df["age_year"] > 59:` .... `elif df["age_year"] > 49:` .... `elif df["age_year"] > 39:` .... `else:` – jsotola Mar 27 '21 at 17:14
  • i corrected 40 and 50 so that it would become >=, but obviously that was not what caused the error – ela rednax Mar 27 '21 at 17:18

0 Answers0