【发布时间】:2023-01-05 02:52:24
【问题描述】:
我发现 pandas groupby-resample 行为的输出不一致。
以这个数据框为例,其中类别 A 在第一天和第二天都有样本,而类别 B 只有在第二天有样本:
df1 = pd.DataFrame(index=pd.DatetimeIndex(
['2022-1-1 1:00','2022-1-2 1:00','2022-1-2 1:00']),
data={'category':['A','A','B']})
# Output:
# category
#2022-01-01 01:00:00 A
#2022-01-02 01:00:00 A
#2022-01-02 01:00:00 B
当我进行 groupby-resample 时,我得到一个在类别和时间上具有多索引的系列:
res1 = df1.groupby('category').resample('1D').size()
#Output:
#category
#A 2022-01-01 1
# 2022-01-02 1
#B 2022-01-02 1
#dtype: int64
但是,如果我再添加一个数据点,以便 B 在第 1 天有一个样本,则返回值是一个数据帧,其类别为单索引,列对应于时间仓:
df2 = pd.DataFrame(index=pd.DatetimeIndex(
['2022-1-1 1:00','2022-1-2 1:00','2022-1-2 1:00','2022-1-1 1:00']),
data={'category':['A','A','B','B']})
res2 = df2.groupby('category').resample('1D').size()
# Output:
# 2022-01-01 2022-01-02
# category
# A 1 1
# B 1 1
这是预期的行为吗?我在 pandas 1.4.2 中重现了这种行为,但找不到错误报告。
【问题讨论】:
标签: pandas pandas-groupby pandas-resample