【发布时间】:2018-08-08 15:28:18
【问题描述】:
我正在尝试连接 Pandas DataFrame 的两列:
df = pd.DataFrame({'A': [2, 1, 3, 4], 'B': ['a', 'b', 'c', 'd']})
(格式化):
A B
0 2 a
1 1 b
2 3 c
3 4 d
尝试sum([df[column] for column in df]) 不起作用,显然是因为您无法将整数(列A)添加到字符串(列B)。
所以我添加了以下几行:
for column in df1:
df1[column] = df1[column].apply(str)
为了确保字符串转换工作正常,我添加了以下语句:
print([df[column].apply(type) for column in df])
哪个产生
In : print([df[column].apply(type) for column in df])
Out:
[0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
3 <class 'str'>
Name: A, dtype: object, 0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
3 <class 'str'>
Name: B, dtype: object]
但是仍然,当我运行sum([df[column] for column in df]) 时,我收到错误TypeError: unsupported operand type(s) for +: 'int' and 'str'。
发生了什么事?
【问题讨论】:
-
“连接”是指字符串连接列以生成一系列字符串
-
预期的输出应该是包含元素“2a”、“1b”、“3c”、“4d”的熊猫系列。我不担心列标题。
标签: python python-3.x pandas tostring