Home > Enterprise >  filtering elements in pandas
filtering elements in pandas

Time:01-29

I'm trying to filter data, in this case, the sex of a group of people, and then calculating the mean of the age of only the people who are mail (previously filtered).

average_age_men = df.loc[df["sex" == "Male"], df["age".mean()]]
print(average_age_men)

This code here should work but keeps throwing the same mistake, KeyError: False (I already checked the post referred to that error). I have no clue of what to do, I feel like it's actually so simple that I feel silly for not being able to do it.

CodePudding user response:

The right syntax is (probably):

average_age_men = df.loc[df["sex"] == "Male", "age"].mean()

CodePudding user response:

You could also try

average_age_men = df[df["sex"] == "Male"]]["age"].mean()
  •  Tags:  
  • Related