当使用
groupby
+apply
调用函数时,我希望从一个DataFrame
转换为一个Series
分组对象,对每个组应用一个以Series
作为输入和输出的函数,并将groupby
+apply
调用的输出赋值为DataFrame
中的一个字段。默认行为是使groupby
+apply
的输出按分组字段进行索引,这会使我无法干净地将它赋回到DataFrame
中。我更喜欢使用Series
作为输入和输出来调用apply
函数,因为这比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
与输入字段保持相同的dtype
。我喜欢transform
保持原始的Index
,虽然我不一定要广播,但也无所谓,因为结果的长度为1。尽管在完整的问题中transform
将boolean
转换为datetime
,而datetime
无法转换回boolean
,但这个答案在精神上是最好的。从R语言的角度来看,我觉得Index
是双刃剑,而dtypes
有点困难,但我喜欢很多其他的东西。 - mef jons