Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将字符串和数字连接成一个字符串_Python_String_Pandas_Concatenation - Fatal编程技术网

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