nfornicole
nfornicole

Reputation: 47

pandas get column average for rows with a certain value?

I can't get the average of values of a column in pandas based on the values of a different column. For example

>>> df
         ID     city     timeDiff
0        1       A       2
1        2       A       3
2        3       A       4     
3        4       B       6
3        5       B       6

What I am trying to get is avg of timeDiff for specific cities like

A : (2+3+4)/3 = 3

B : (6+6)/2 = 6

I understand I can get column specific average via df[columnName].mean() but I am not sure how to first group on city name and then find the average ?

Upvotes: 2

Views: 2699

Answers (2)

user9270170
user9270170

Reputation:

You can try:

import pandas as pd
d = {'ID': [1,2,3,4,5], 'city': ['A','A','A','B','B'],'timeDiff':[2,3,4,6,6]}
df = pd.DataFrame(data=d)
mean_df = df.groupby(['city'])['timeDiff'].mean()

Upvotes: 0

noah
noah

Reputation: 2786

Use pandas.core.groupby.GroupBy.mean:

df.groupby("city")["timeDiff"].mean()

Upvotes: 3

Related Questions