简体   繁体   中英

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

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.

df.assign(c = lambda d: str(d['x']) + str(d['y']))

在此处输入图像描述

I was expecting to see the column 'c' to have ['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.

If you want use .assign with lambda, you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM