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 !
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.
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.
mean() function in the Pandas library can be used to find the mean of a series.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With