Lyu Keting
Lyu Keting

Reputation: 83

python: pandas: filter one column and get the average of another column

I have a python pandas dataframe like:

a  b
1  5
3  6
1  7
2  8
2  34
3  35
1  54
3  123
4  2353
... ....

I want get the mean of value in b when a has different value. For example, when a = 1, b = 5, 7, 54, so the mean(a=1) = (5 + 7 + 54)/3; when a = 2, b = 8, 34, so the mean(a=2) = (8 + 34)/2;

my try is

aaa = []
for v in df['a']:
    aaa.append(np.mean(df['b'])
print (aaa)

but it's not right. hope you can help me. thank you !

Upvotes: 6

Views: 9146

Answers (1)

akuiper
akuiper

Reputation: 215107

You can use groupby for aggregation:

df.groupby('a').b.mean()

#a
#1      22.000000
#2      21.000000
#3      54.666667
#4    2353.000000
#Name: b, dtype: float64

Upvotes: 11

Related Questions