2017-05-24 1876 views
1

我正在使用一個熊貓數據框並嘗試將多個字符串和數字連接成一個字符串。Python 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') 
+2

嘗試改變'拉姆達X: ''。加入(X)''以拉姆達X: ''。加入(STR(X))' –

回答

3

考慮數據框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 

可以使用astype(str)領先的lambda

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 
+0

這是偉大的!謝謝 –

1

您必須將列類型轉換爲字符串。

import pandas as pd 
df2 = pd.DataFrame({'Col1': ['a', 'b', 1], 'Col2': ['a', 'b', 1]}) 
df2.apply(lambda x: ', '.join(x.astype('str')), axis=1) 
2
In [75]: df2 
Out[75]: 
    Col1 Col2 Col3 
0 a a x 
1 b b y 
2 1 1 2 

In [76]: df2.astype(str).add(', ').sum(1).str[:-2] 
Out[76]: 
0 a, a, x 
1 b, b, y 
2 1, 1, 2 
dtype: object