需要确认Pandas Groupby transform的行为:
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two'],
'C' : [1, 5, 5, 2, 5, 5],
'D' : [2.0, 5., 8., 1., 2., 9.]})
grouped = df.groupby('A')
grouped.transform(lambda x: (x - x.mean()) / x.std())
C D
0 -1.154701 -0.577350
1 0.577350 0.000000
2 0.577350 1.154701
3 -1.154701 -1.000000
4 0.577350 -0.577350
5 0.577350 1.000000
它没有指定应用lambda函数的列。pandas如何决定哪些列(在本例中是C和D)应用该函数?为什么它不应用于B列并抛出错误?
为什么输出不包括A列和B列?
GroupBy.transform
为每个组中的每个列调用指定的函数(因此B
,C
和D
-而不是A
,因为这是您分组的依据)。但是,您调用的函数(mean
和std
)只处理数值,因此如果dtype
不是数值,Pandas将跳过该列。字符串列是dtype
object
,这不是数字,所以B
被删除,剩下C
和D
。
你应该在运行代码时得到警告-
FutureWarning: Dropping invalid columns in DataFrameGroupBy.transform is deprecated. In a future version, a TypeError will be raised. Before calling .transform, select only columns which should be valid for the transforming function.
正如它所指示的,您需要在处理之前选择要处理的列,以避免警告。您可以通过在调用transform
:
[['C', 'D']]
(例如,选择您的C
和D
列)来做到这一点:grouped[['C', 'D']].transform(lambda x: (x - x.mean()) / x.std())
# ^^^^^^^^^^^^ important