Skip to main content
 首页 » 编程设计

Python Pandas 将字符串和数字连接成一个字符串

2025年05月04日2252php

我正在使用 pandas 数据框并尝试将多个字符串和数字连接成一个字符串。

这行得通

df1 = pd.DataFrame({'Col1': ['a', 'b', 'c'], 'Col2': ['a', 'b', 'c']}) 
df1.apply(lambda x: ', '.join(x), axis=1) 
 
0    a, a 
1    b, b 
2    c, c 

如何使它像 df1 一样工作?

df2 = pd.DataFrame({'Col1': ['a', 'b', 1], 'Col2': ['a', 'b', 1]}) 
df2.apply(lambda x: ', '.join(x), axis=1) 
 
TypeError: ('sequence item 0: expected str instance, int found', 'occurred at index 2') 

请您参考如下方法:

考虑数据框 df

np.random.seed([3,1415]) 
df = pd.DataFrame( 
    np.random.randint(10, size=(3, 3)), 
    columns=list('abc') 
) 
 
print(df) 
 
   a  b  c 
0  0  2  7 
1  3  8  7 
2  0  6  8 

您可以在 lambda 之前使用 astype(str)

df.astype(str).apply(', '.join, 1) 
 
0    0, 2, 7 
1    3, 8, 7 
2    0, 6, 8 
dtype: object 

使用理解

pd.Series([', '.join(l) for l in df.values.astype(str).tolist()], df.index) 
 
0    0, 2, 7 
1    3, 8, 7 
2    0, 6, 8 
dtype: object