Mati
Mati

Reputation: 39

filtering elements in pandas

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.

Upvotes: 1

Views: 31

Answers (2)

Jorge Alvarez
Jorge Alvarez

Reputation: 104

You could also try

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

Upvotes: 0

Corralien
Corralien

Reputation: 120409

The right syntax is (probably):

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

Upvotes: 1

Related Questions