Skip to main content
 首页 » 编程设计

python之如何将给定 Pandas 数据帧行中的所有(字符串)值连接到一个字符串

2025年05月04日16yxwkf

我有一个看起来像这样的 Pandas 数据框:

     0        1            2        3       4 
0    I        want         to       join    strings   
1    But      only         in       row     1 

所需的输出应如下所示:

     0        1      2        3       4       5 
1    But      only   in       row     1       I want to join strings 

如何将这些字符串连接成一个联合字符串?

请您参考如下方法:

IIUC,通过使用 apply ,join

df.apply(lambda x :' '.join(x.astype(str)),1) 
Out[348]:  
0    I want to join strings 
1         But only in row 1 
dtype: object 

然后你可以分配它们

df1=df.iloc[1:] 
df1['5']=df.apply(lambda x :' '.join(x.astype(str)),1)[0] 
df1 
Out[361]:  
     0     1   2    3  4                       5 
1  But  only  in  row  1  I want to join strings 

对于时间:

%timeit df.apply(lambda x : x.str.cat(),1) 
1 loop, best of 3: 759 ms per loop 
%timeit df.apply(lambda x : ''.join(x),1) 
1 loop, best of 3: 376 ms per loop 
 
 
df.shape 
Out[381]: (3000, 2000)