Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 926
Lyu Keting Avatar asked Dec 31 '16 03:12

Lyu Keting


People also ask

How do I find the average of two columns in pandas?

To get column average or mean from pandas DataFrame use either mean() and describe() method. The DataFrame. mean() method is used to return the mean of the values for the requested axis.

How would you find out the mean of one column WRT another?

We can find the mean of one column concerning another by using ColMeans() function along with sapply() function. It is always helpful to find the mean of the multiple columns. Wed can also find the mean of multiple columns through Dplyr functions.

How do you calculate average in pandas?

mean() function in the Pandas library can be used to find the mean of a series.

How does pandas calculate average by group by?

Pandas Groupby Mean To get the average (or mean) value of in each group, you can directly apply the pandas mean() function to the selected columns from the result of pandas groupby.


1 Answers

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
like image 181
Psidom Avatar answered Nov 03 '22 00:11

Psidom