Concatenate two numerical values to make a new column using pandas?

橙三吉。 提交于 2019-11-30 17:20:20

问题


I have two columns in my dataframe.

var1    var2
01       001

I would like to create a third column that joins them together:

var1    var2    var3
01       001    01001

Does anyone know how to do this? Thank you!


回答1:


You can use simple concanecate by + with casting by astype:

df['var3'] = df.var1.astype(str) + df.var2.astype(str)
print df
  var1 var2   var3
0   01  001  01001

If type of both columns is string casting is omited:

print type(df.loc[0,'var1'])
<type 'str'>
print type(df.loc[0,'var2'])
<type 'str'>

df['var3'] = df.var1 + df.var2
print df
  var1 var2   var3
0   01  001  01001



回答2:


Convert to both columns to string and then join both the columns to form the third column.

Code:

df['var1']=df['var1'].astype(str)
df['var2']=df['var2'].astype(str)
df['var3'] = df[['var1', 'var2']].apply(lambda x: ''.join(x), axis=1)


来源:https://stackoverflow.com/questions/36774602/concatenate-two-numerical-values-to-make-a-new-column-using-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!