I have two column, age and income. There are some income values in same age. How do I get the average from specific age?
If I try to use
df.groupby('age')['income'].mean()
I will get a dataframe, How do I get a value for a specific age?
I have two column, age and income. There are some income values in same age. How do I get the average from specific age?
If I try to use
df.groupby('age')['income'].mean()
I will get a dataframe, How do I get a value for a specific age?
You're right that the groupby
method followed by taking the mean will give you a series with the average income for each age in your DataFrame. If you want to get the average income for a specific age, you need to pass the specific age you're interested in.
I assume that you want the average income for an age of 30. You would do:
average_income_age_30 = df.groupby('age')['income'].mean().loc[30]
This will first perform the grouping and mean calculation, and then use the loc
method to retrieve the value for age 30.
Or, you can assign the result of the groupby
and mean
to a variable and then use that:
average_incomes_by_age = df.groupby('age')['income'].mean()
average_income_age_30 = average_incomes_by_age.loc[30]