Adding spaces between strings after sum()

此生再无相见时 提交于 2021-02-10 18:26:08

问题


Assuming that I have the following pandas dataframe:

>>> data = pd.DataFrame({ 'X':['a','b'], 'Y':['c','d'], 'Z':['e','f']})  
   X Y Z
 0 a c e
 1 b d f

The desired output is:

0    a c e
1    b d f

When I run the following code, I get:

>>> data.sum(axis=1)
0    ace
1    bdf

So how do I add columns of strings with space between them?


回答1:


Use apply per rows by axis=1 and join:

a = data.apply(' '.join, axis=1)
print (a)
0    a c e
1    b d f
dtype: object

Another solution with add spaces, sum and last str.rstrip:

a = data.add(' ').sum(axis=1).str.rstrip()
#same as
#a = (data + ' ').sum(axis=1).str.rstrip()
print (a)
0    a c e
1    b d f
dtype: object



回答2:


You can do as follow :

data.apply(lambda x:x + ' ').sum(axis=1)

The output is :

0    a c e 
1    b d f 
dtype: object


来源:https://stackoverflow.com/questions/45188605/adding-spaces-between-strings-after-sum

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