各种类型的Pandas Sum DataFrame列

时间:2018-08-08 15:28:19

标签: python python-3.x pandas tostring

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

这是怎么回事?

3 个答案:

答案 0 :(得分:4)

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

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

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

这会将所有列键入strdf.astype(str)),然后使用sum逐行连接(axis=1

答案 1 :(得分:4)

使用

In [99]: df.A.astype(str) + df.B
Out[99]:
0    2a
1    1b
2    3c
3    4d
dtype: object

使用apply替代,可能会很慢。

In [106]: df.apply(lambda x: '{A}{B}'.format(**x), axis=1)
Out[106]:
0    2a
1    1b
2    3c
3    4d
dtype: object

@JonClementsformat_map

有很好的选择
In [124]: df.apply('{A}{B}'.format_map, axis=1)
Out[124]:
0    2a
1    1b
2    3c
3    4d
dtype: object

答案 2 :(得分:2)

如果您对性能感兴趣,请使用f-strings和列表理解。

pd.Series([f'{i}{j}' for i,j in zip(df.A, df.B)])

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

由于熊猫处理字符串的效率较低,相对而言,这是一个非常快速的选择。