Pandas 数据框:创建一个新列,该列是使用其他 2 个列的自定义函数 [英] Pandas dataframe: creating a new column that is a custom function using 2 other columns
问题描述
考虑存储在 Pandas DataFrame dfX
中的以下数据集:
Consider the following data set stored in a pandas DataFrame dfX
:
A B
1 2
4 6
7 9
我有一个函数:
def someThingSpecial(x,y)
# z = do something special with x,y
return z
我现在想在 df
中创建一个包含计算出的 z 值的新列
I now want to create a new column in df
that bears the computed z value
查看其他 SO 示例,我尝试了多种变体,包括:
Looking at other SO examples, I've tried several variants including:
dfX['C'] = dfX.apply(lambda x: someThingSpecial(x=x['A'], y=x['B']), axis=1)
返回错误.这样做的正确方法是什么?
Which returns errors. What is the right way to do this?
推荐答案
这在 v0.21 上似乎对我有用.看一看-
This seems to work for me on v0.21. Take a look -
df
A B
0 1 2
1 4 6
2 7 9
def someThingSpecial(x,y):
return x + y
df.apply(lambda x: someThingSpecial(x.A, x.B), 1)
0 3
1 10
2 16
dtype: int64
您可能想尝试将您的 Pandas 版本升级到最新的稳定版本(目前为 0.21).
You might want to try upgrading your pandas version to the latest stable release (0.21 as of now).
这是另一种选择.您可以矢量化您的函数.
Here's another option. You can vectorise your function.
v = np.vectorize(someThingSpecial)
v
现在接受数组,但单独对每对元素进行操作.请注意,这只是隐藏了循环,就像 apply 一样,但要干净得多.现在,您可以这样计算 C
-
v
now accepts arrays, but operates on each pair of elements individually. Note that this just hides the loop, as apply does, but is much cleaner. Now, you can compute C
as so -
df['C'] = v(df.A, df.B)
这篇关于Pandas 数据框:创建一个新列,该列是使用其他 2 个列的自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!