Skip to main content
 首页 » 编程设计

python之在 sum() 之后的字符串之间添加空格

2025年05月04日39shanyou

假设我有以下 Pandas 数据框:

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

期望的输出是:

0    a c e 
1    b d f 

当我运行以下代码时,我得到:

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

那么如何添加字符串列并在它们之间留有空格?

请您参考如下方法:

使用apply每行 axis=1 和 join:

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

另一种解决方案 add空格,sum最后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