python - pandas dataframe,如何获得某个索引的平均值

标签 python pandas

例如,我有一个这样的数据框:

Age Gender  
20   Male  
10   Male  
18   Female  
15   Male  
19   Female  
17   Female  

我怎样才能像这样的 DataFrame:

Age  Gender  
15   Male  
18   Female  

新DataFrame中的年龄分别是对应Gender的旧DataFrame的平均年龄。

最佳答案

In [51]: df.groupby('Gender', as_index=False).Age.mean()
Out[51]:
   Gender  Age
0  Female   18
1    Male   15

How can I make the result DataFrame a Series with Gender as keys/index?

In [61]: s = df.groupby('Gender').Age.mean()

In [62]: s
Out[62]:
Gender
Female    18
Male      15
Name: Age, dtype: int64

In [63]: type(s)
Out[63]: pandas.core.series.Series

关于python - pandas dataframe,如何获得某个索引的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504553/

相关文章:

python - 多个条形图的单个图例 matplotlib

python - 使用python从BytesIO创建一个excel文件

python - 绑定(bind)到 Enter 的 Tkinter 按钮立即执行

python - 如何在 python 3.5 中安装 opencv 库?

python - 按作为实例属性的值对字典进行排序

python - 用向量 [n,] 填充逻辑矩阵 [r,n]

python - 使用多个条件屏蔽 DataFrame

python - 从 django 中的表中过滤掉空值

python - 使用 Gekko 划分楼层

python-2.7 - Geopandas 数据框/矩阵 - 过滤/删除 NaN/False 值