首页 > 解决方案 > Pandas Sum DataFrame 各种类型的列

问题描述

我正在尝试连接 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'

到底是怎么回事?

标签: pythonpython-3.xpandastostring

解决方案


IIUC,您可以像这样连接您的列:

df.astype(str).sum(axis=1)

0    2a
1    1b
2    3c
3    4d
dtype: object

这会将所有列转换为类型str( df.astype(str)),然后用于sum逐行连接 ( axis=1)


推荐阅读