Python将字符串和数字连接成一个字符串
我正在使用熊猫数据帧,并试图将多个字符串和数字连接成一个字符串 这很有效Python将字符串和数字连接成一个字符串,python,string,pandas,concatenation,Python,String,Pandas,Concatenation,我正在使用熊猫数据帧,并试图将多个字符串和数字连接成一个字符串 这很有效 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': [
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')
必须将列类型转换为字符串
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)
必须将列类型转换为字符串
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)
以数据帧df为例
您可以在lambda之前使用astypestr
运用理解力
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
以数据帧df为例
您可以在lambda之前使用astypestr
运用理解力
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
尝试更改lambda x:','。joinx为lambda x:','。joinstrxtry更改lambda x:','。joinx为lambda x:','。joinstrx这太棒了!谢谢这太好了!非常感谢。
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