How to cat two columns (float) to columns quickly and efficiently in pandas dataframe?

I want to get a new cat two column (float or int) like below,

So, who has an idea?

I think mine is too complicated

a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
   a   b   c
0  1   2   3
1  3   4   5
2  5   6   6
3  7   8   5
4  9  10  10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

      

+3


source to share


3 answers


Use astype

to convert to str

:

#if need select columns by position with iloc
abc['new'] = abc.iloc[:,0].astype(str) + '::' + abc.iloc[:,1].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

      




#if need select by column names
abc['new'] = abc['a'].astype(str) + '::' + abc['b'].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

      

Solution with str.cat

:

abc['new'] = abc['a'].astype(str).str.cat(abc['b'].astype(str), sep='::')
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

      

+3


source


You can also do something like this using map

abc['d'] = abc['a'].map(str) +'::'+ abc['b'].map(str)
print(abc)

      



output:

   a   b   c      d
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

      

+3


source


how to use apply

?

abc['new'] = abc.apply(lambda x: '{}::{}'.format(x['a'],x['b']), axis=1)

      

it's a simple one-liner.

+1


source







All Articles