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

后端 未结 2 874
滥情空心
滥情空心 2021-01-02 18:49

I have two columns in my dataframe.

var1    var2
01       001

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



        
2条回答
  •  Happy的楠姐
    2021-01-02 19:37

    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'])
    
    print type(df.loc[0,'var2'])
    
    
    df['var3'] = df.var1 + df.var2
    print df
      var1 var2   var3
    0   01  001  01001
    

提交回复
热议问题