python - 如何使用按另一列分组的 Pandas Dataframe 获取分组大小的方法?

标签 python pandas

假设我有这样一个数据集:

import pandas as pd

raw_data = {
    'entrytype': ['a', 'a', 'b', 'c', 'c', 'c', 'd'],
    'year': [2000, 2000, 2000, 2001, 2001, 2001, 2001],
}

df = pd.DataFrame.from_dict(raw_data)

我想要每年不同entrytype的数量的平均值(entrytype只是为了示例,真实数据集有其他列和其他名称)。entrytype p>

现在,如果我这样做:df.groupby(['entrytype', 'year']).size() 我会得到 entrytypes 的数量Pandas Series像这样:

entrytype  year
a          2000    2
b          2000    1
c          2001    3
d          2001    1
dtype: int64

我需要的是每年这些数字的平均值,如下所示:

year
2000    1.5
2001    2

我曾尝试用 Pandas 来做这件事,但无法按年份分组,因为系列是一维的,因此不允许分组。我最终使用 Python 字典并“手动”计算平均值,但必须有更好的方法来执行此操作,即使用 Pandas。

那么,我该如何使用 Pandas API 做到这一点呢?

最佳答案

这应该可行

df.groupby(['entrytype', 'year']).size().groupby(level=1).mean()

year
2000    1.5
2001    2.0
dtype: float64

关于python - 如何使用按另一列分组的 Pandas Dataframe 获取分组大小的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23389965/

相关文章:

python - Qtimer 不工作

python - 使除法结果为小数点后两位的 float (Python)

python - 通过 Pandas DataFrame 计算每行零的数量?

Python更改csv文件中特定列的字符串(日期)格式

python - 如何根据pandas DataFrame中的说话者#将单词分组为句子

python - Pandas - 根据百分比获取前 n 行

将行作为列索引、将列作为行索引的 Pythonic 方法

python - Py.test fixture : Use function fixture in scope fixture

python - 如何根据时差分离 Pandas 数据框?

python - 如何在 Python 3 中使用过滤器、映射和归约