假设我有这样一个数据集:
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)
我想要每年不同entrytypes数量的平均值(entrytypes只是举个例子,真实的数据集有其他列和其他名称)。你知道吗
现在,如果我这样做:df.groupby(['entrytype', 'year']).size()
我得到一个Pandas Series中入口类型的数量如下:
entrytype year
a 2000 2
b 2000 1
c 2001 3
d 2001 1
dtype: int64
我需要的是每年这些数字的平均值,比如:
year
2000 1.5
2001 2
我曾经试着用熊猫来做这个,但是不能按年份分组,因为这个系列是1d,因此不允许分组。最后,我使用了Python字典并“手工”计算了平均值,但肯定有更好的方法,使用Pandas。你知道吗
那么,如何使用Pandas API实现这一点呢?你知道吗
这应该管用
相关问题 更多 >
编程相关推荐