Python Pandas:如何在groupby / transform操作内部向数据框添加全新的列
我想在数据中标记一些分位数,对于DataFrame的每一行,我希望在名为“ xtile”的新列中的条目保持该值。
例如,假设我创建一个像这样的数据框:
import pandas, numpy as np
dfrm = pandas.DataFrame({'A':np.random.rand(100),
'B':(50+np.random.randn(100)),
'C':np.random.randint(low=0, high=3, size=(100,))})
假设我编写了自己的函数来计算数组中每个元素的五分位数。我对此有自己的功能,但例如仅参考scipy.stats.mstats.mquantile。
import scipy.stats as st
def mark_quintiles(x, breakpoints):
# Assume this is filled in, using st.mstats.mquantiles.
# This returns an array the same shape as x, with an integer for which
# breakpoint-bucket that entry of x falls into.
现在,真正的问题是如何使用transform
向数据添加新列。像这样:
def transformXtiles(dataFrame, inputColumnName, newColumnName, breaks):
dataFrame[newColumnName] = mark_quintiles(dataFrame[inputColumnName].values,
breaks)
return dataFrame
接着:
dfrm.groupby("C").transform(lambda x: transformXtiles(x, "A", "A_xtile", [0.2, 0.4, 0.6, 0.8, 1.0]))
问题是上述代码不会添加新列“ A_xtile”。它只是返回我的数据帧不变。如果我首先添加一个充满虚拟值的列,例如NaN,称为“ A_xtile”,则它
会 成功覆盖此列以包含正确的五分位数标记。
但是,必须首先在该列中写一些我可能想要即时添加的内容,这非常不便。
请注意,apply
这里的简单方法不起作用,因为它不知道如何理解每个组可能不同大小的结果数组。
-
您遇到什么问题
apply
?它适用于此玩具示例,并且组长不同:In [82]: df Out[82]: X Y 0 0 -0.631214 1 0 0.783142 2 0 0.526045 3 1 -1.750058 4 1 1.163868 5 1 1.625538 6 1 0.076105 7 2 0.183492 8 2 0.541400 9 2 -0.672809 In [83]: def func(x): ....: x['NewCol'] = np.nan ....: return x ....: In [84]: df.groupby('X').apply(func) Out[84]: X Y NewCol 0 0 -0.631214 NaN 1 0 0.783142 NaN 2 0 0.526045 NaN 3 1 -1.750058 NaN 4 1 1.163868 NaN 5 1 1.625538 NaN 6 1 0.076105 NaN 7 2 0.183492 NaN 8 2 0.541400 NaN 9 2 -0.672809 NaN