pandas 数据框,如何获取某个索引值的平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41504553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:43:34  来源:igfitidea点击:

pandas dataframe, how to get average of a value over a certain index

pythonpandas

提问by Albert X.W.

For example, I have a dataframe like this:

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

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

How can I can a DataFrame like:

我怎样才能像 DataFrame 这样:

Age  Gender  
15   Male  
18   Female  

The age in the new DataFrame is the average age of the old DataFrame with corresponding Gender respectively.

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

回答by MaxU

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?

如何使结果 DataFrame 成为以 Gender 作为键/索引的系列?

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