【问题标题】:pandas groupby().apply() grouping the same group again and again under different namespandas groupby().apply() 以不同的名称一次又一次地对同一组进行分组
【发布时间】:2023-01-19 03:04:23
【问题描述】:

我有一个由各种列组成的熊猫数据。其中有“分支”和“条形码”,我想通过它们对数据框进行分组并应用一个函数。我以前做过数千次的事情。

但这次它表现出我从未见过的行为。它不是将每个组发送到函数,而是一遍又一遍地发送相同的组。只有组的名称按预期更改。

为了展示这个问题,我打印出组名(其中包含不断变化的 groupby 键)和第一行的条形码和分支,它们应该与名称相同但不是。

这是基本代码:

def main_features(df):
    print(df.name)
    print(df[['barcode', 'branch']].iloc[0])

df5 = df4.groupby(['branch', 'barcode']).apply(main_features)

注意输出:

(1, 90162800)
barcode    90162800
branch            1
Name: 1, dtype: int64
(1, 38000232176)
barcode    90162800
branch            1
Name: 3, dtype: int64
(1, 38000232183)
barcode    90162800
branch            1
Name: 4, dtype: int64
(1, 3014260280772)
barcode    90162800
branch            1
Name: 18, dtype: int64
(1, 3014260289287)
barcode    90162800
branch            1
Name: 19, dtype: int64
(1, 4015400562818)
barcode    90162800
branch            1
Name: 44, dtype: int64
(1, 4015400563747)
barcode    90162800
branch            1
Name: 45, dtype: int64
(1, 4015400563846)
barcode    90162800
branch            1
Name: 46, dtype: int64
(1, 4015400564324)
...
...
...and so on

请注意,条形码和分支在 df.name 中发生了变化。但实际分支和条形码是不变的。有史以来最奇怪的熊猫行为。

有任何想法吗?

【问题讨论】:

    标签: python pandas group-by


    【解决方案1】:

    我发现了问题,虽然我真的无法解释它。 在我的函数结束时,在返回 DF 之前,我删除了一列。 似乎是那个下拉列导致了所有这些有趣的行为,尽管我确定我不知道为什么......

    我的职能是...

    def main_features(df):
        print(df.name)
        print(df[['barcode', 'branch']].iloc[0])
        ...
        ...
        ...
        **df = df.drop('temp_sales', axis=1)**
        return df
    

    删除 drop 方法解决了问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2015-07-04
      • 2015-08-18
      • 1970-01-01
      相关资源
      最近更新 更多