我有以下 df 数据框(pandas):
attribute
2017-01-01 a
2017-01-01 a
2017-01-05 b
2017-02-01 a
2017-02-10 a
其中第一列是一个非唯一的 datetime 索引,我想每周计算 a 和 b 的数量。如果我尝试 df.attribute.resample('W').count() 将会出现错误,因为条目重复。
我该怎么做?
请您参考如下方法:
df=df.reset_index()
df.groupby([df['index'].dt.week,'attribute']).count()
Out[292]:
index
index attribute
1 b 1
5 a 1
6 a 1
52 a 2
或者
df.groupby([df.index.get_level_values(0).week,'attribute'])['attribute'].count()
Out[303]:
attribute
1 b 1
5 a 1
6 a 1
52 a 2
Name: attribute, dtype: int64
