【发布时间】: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 中发生了变化。但实际分支和条形码是不变的。有史以来最奇怪的熊猫行为。
有任何想法吗?
【问题讨论】: