【问题标题】:Inconsistent output for pandas groupby-resample with missing values in first time binpandas groupby-resample 的输出不一致,第一次 bin 中缺少值
【发布时间】: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


    【解决方案1】:

    我向 pandas 提交了错误报告 46826。

    【讨论】:

      【解决方案2】:

      在这两种情况下,结果都应该是 SeriesMultiIndex。有一个错误导致 df.groupby.resample.size 在所有组都具有相同索引的情况下返回宽 DF。这已在 master 分支上修复。感谢您打开issue

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多