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

3

12

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!

Whirlabout answered 21/4, 2016 at 15:47 Comment(0)
Z
17

You can use simple concatenate 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
Zobias answered 21/4, 2016 at 15:48 Comment(0)
P
1

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)
Plunder answered 21/4, 2016 at 16:2 Comment(0)
E
0

If you want one-liner:

df['var3'] = df[['var1', 'var2']].astype(str).apply(lambda x: ''.join(x), axis=1)
Ectoparasite answered 30/6, 2023 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.