[英]Understand assign behaviour in pandas using lambda
I have created a simple pandas dataframe using python 3.8.5 and pandas version 1.2.1我使用 python 3.8.5 和 Z3A43B4F8832915D94022C0EF 版本创建了一个简单的 pandas dataframe。
df = pd.DataFrame({'x' : [1,2], 'y' : [3,4]})
I would like to perform a string addition of the 2 columns into the third using assign function.我想使用assign function将2列添加到第三列中。
df.assign(c = lambda d: str(d['x']) + str(d['y']))
I was expecting to see the column 'c' to have ['13', '24']我期待看到列 'c' 有 ['13', '24']
Can someone please help me understand this behavior?有人可以帮我理解这种行为吗?
With str(d['x'])
you'll get string representation of pd.Series
( similar when you do print(df['x'])
), which isn't what you want.使用str(d['x'])
您将获得pd.Series
的字符串表示形式(在您执行print(df['x'])
时类似),这不是您想要的。
If you want use .assign
with lambda, you can do:如果您想将.assign
与 lambda 一起使用,您可以执行以下操作:
df = pd.DataFrame({"x": [1, 2], "y": [3, 4]})
print(df.assign(c=lambda d: d["x"].astype(str) + d["y"].astype(str)))
Prints:印刷:
x y c
0 1 3 13
1 2 4 24
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.