Pandas 函数以在新列中生成新值
我不熟悉python 3和熊猫。我试图在数据框中添加一个新列,其中的值是两个现有列之间的差值。 我目前的代码是:Pandas 函数以在新列中生成新值,pandas,lambda,apply,Pandas,Lambda,Apply,我不熟悉python 3和熊猫。我试图在数据框中添加一个新列,其中的值是两个现有列之间的差值。 我目前的代码是: import pandas as pd import io from io import StringIO x="""a,b,c 1,2,3 4,5,6 7,8,9""" with StringIO(x) as df: new=pd.read_csv(df) print (new) y=new.copy() y.loc[:,"d"]=0 # My lambda fu
import pandas as pd
import io
from io import StringIO
x="""a,b,c
1,2,3
4,5,6
7,8,9"""
with StringIO(x) as df:
new=pd.read_csv(df)
print (new)
y=new.copy()
y.loc[:,"d"]=0
# My lambda function is completely wrong, but I don't know how to make it right.
y["d"]=y["d"].apply(lambda x:y["a"]-y["b"], axis=1)
期望输出为
a、b、c、d
1 2 3-1
4 5 6-1
7 8 9-1
有人知道我怎样才能使我的代码工作吗
谢谢您的帮助。您需要
y
仅用于数据帧
用于轴=1
用于按行处理:
y["d"]= y.apply(lambda x:x["a"]-x["b"], axis=1)
为了更好地进行调试,可以创建自定义函数:
def f(x):
print (x)
a = x["a"]-x["b"]
return a
y["d"]= y.apply(f, axis=1)
a 1
b 2
c 3
Name: 0, dtype: int64
a 4
b 5
c 6
Name: 1, dtype: int64
a 7
b 8
c 9
Name: 2, dtype: int64
如果只需要减去列,则更好的解决方案:
y["d"] = y["a"] - y["b"]
print (y)
a b c d
0 1 2 3 -1
1 4 5 6 -1
2 7 8 9 -1
非常感谢您的回复。它确实有效。请问在这种情况下x代表什么?它是指y的每一行吗?确切地说,它是每一行,因为
axis=1
。如果轴=0,则为每列。