当使用 groupby + apply 调用函数时,我想从 DataFrame 转到 Series groupby 对象,将一个函数应用于每个组,该函数将 Series 作为输入并返回 Series 作为输出,然后分配 groupby 的输出> + apply 调用作为 DataFrame 中的一个字段。 默认行为是让 groupby + apply 的输出被分组字段索引,这阻止我将它干净地分配回 DataFrame .我希望我用 apply 调用的函数将 Series 作为输入并返回 Series 作为输出;我认为它比 DataFrame 到 DataFrame 更干净一些。 (这不是获得此示例结果的最佳方式;实际应用程序非常不同。)
import pandas as pd
df = pd.DataFrame({
'A': [999, 999, 111, 111],
'B': [1, 2, 3, 4],
'C': [1, 3, 1, 3]
})
def less_than_two(series):
# Intended for series of length 1 in this case
# But not intended for many-to-one generally
return series.iloc[0] < 2
output = df.groupby(['A', 'B'])['C'].apply(less_than_two)
我希望output上的索引和df一样,否则无法赋值 到 df(干净利落):
df['Less_Than_Two'] = output
output.index = df.index 之类的东西看起来太丑了,使用 group_keys 参数似乎不起作用:
output = df.groupby(['A', 'B'], group_keys = False)['C'].apply(less_than_two)
df['Less_Than_Two'] = output
请您参考如下方法:
transform返回带有原始 index 的结果,正如您所要求的那样。它将在组的所有元素中广播相同的结果。 警告,请注意 dtype 可能会被推断为其他内容。您可能需要自己转换。
在这种情况下,为了添加另一列,我会使用 assign
df.assign(
Less_Than_Two=df.groupby(['A', 'B'])['C'].transform(less_than_two).astype(bool))
A B C Less_Than_Two
0 999 1 1 True
1 999 2 3 False
2 111 3 1 True
3 111 4 3 False
