如何计算多索引数据帧中每天的行数?

2024-03-29 10:53:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有两级多重索引的数据帧。第一级date是DatetimeIndex,第二级name只是一些字符串。数据间隔10分钟。在

如何在这个多重索引的第一级按日期分组并计算每天的行数?

我怀疑DatetimeIndex耦合到多索引中会给我带来问题,因为

data.groupby(pd.TimeGrouper(freq='D')).count()

给了我

^{pr2}$

我也试过写作

data.groupby(data.index.levels[0].date).count()

从而导致

ValueError: Grouper and axis must be same length

例如,我如何使grouper变长(即,包含重复的索引值,而忽略这些值,现在会使它比轴短)?在

谢谢!在


Tags: 数据字符串namedatadateindex间隔count
2条回答

假设数据帧如下所示

d=pd.DataFrame([['Mon','foo',3],['Tue','bar',6],['Wed','qux',9]],
               columns=['date','name','amount'])\
              .set_index(['date','name'])

只能为此分组操作从索引中删除名称

^{pr2}$

您可以在Grouper中使用level关键字。(另请注意,TimeGrouper已弃用)。这个参数是

the level for the target index.

示例数据帧:

dates = pd.date_range('2017-01', freq='10MIN', periods=1000)
strs = ['aa'] * 1000
df = pd.DataFrame(np.random.rand(1000,2), index=pd.MultiIndex.from_arrays((dates, strs)))

解决方案:

^{pr2}$

更新:您在评论中指出,您希望删除的结果计数为零。例如,假设您的数据帧实际上丢失了几天:

df = df.drop(df.index[140:400])
print(df.groupby(pd.Grouper(freq='D', level=0)).count())
              0    1
2017-01-01  140  140
2017-01-02    0    0
2017-01-03   32   32
2017-01-04  144  144
2017-01-05  144  144
2017-01-06  144  144
2017-01-07  136  136

据我所知,没有办法排除.count内的零计数。相反,您可以使用上面的结果来删除0。在

第一个解决方案(可能不太可取,因为当引入np.nan时,它将和int结果转换为float,这可能是

res = df.groupby(pd.Grouper(freq='D', level=0)).count()
res = res.replace(0, np.nan).dropna()

在我看来,第二个更好的解决方案是here

res = res[(res.T != 0).any()]
print(res) # notice - excludes 2017-01-02
              0    1
2017-01-01  140  140
2017-01-03   32   32
2017-01-04  144  144
2017-01-05  144  144
2017-01-06  144  144
2017-01-07  136  136

.any来自NumPy,被移植到pandas,当请求的轴上有任何元素为True时返回True。在

相关问题 更多 >