Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas GroupBy with mean

The below code works for the total of each column, but I want to work out the mean for each species.

# Read data file into array
data = numpy.genfromtxt('data/iris.csv', delimiter=',')
# picking the first column of data
firstcol = data[:,0]
meanfirstcol = numpy.mean(data[:,0]) #defining meanfirstcol
print("Mean of First Column is:", meanfirstcol)
like image 251
C. Drummond Avatar asked Nov 20 '25 04:11

C. Drummond


1 Answers

With pandas, this is pretty easy. You'd just need to groupby on the species column -

import seaborn as sns
df = sns.load_dataset('iris')

df.groupby('species').mean()
            sepal_length  sepal_width  petal_length  petal_width
species                                                         
setosa             5.006        3.428         1.462        0.246
versicolor         5.936        2.770         4.260        1.326
virginica          6.588        2.974         5.552        2.026
like image 67
cs95 Avatar answered Nov 22 '25 18:11

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!