Pandas 对各种类型的 DataFrame 列求和
Pandas Sum DataFrame Columns of various types
我正在尝试连接 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'
。
这是怎么回事?
IIUC,您可以像这样连接您的列:
df.astype(str).sum(axis=1)
0 2a
1 1b
2 3c
3 4d
dtype: object
这会将所有列转换为类型 str
(df.astype(str)
),然后使用 sum
按行连接 (axis=1
)
使用
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
有一个很好的选择 format_map
In [124]: df.apply('{A}{B}'.format_map, axis=1)
Out[124]:
0 2a
1 1b
2 3c
3 4d
dtype: object
如果您对性能感兴趣,请使用 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
由于 pandas 处理字符串的效率低下,相对而言,这将是一个非常快速的选择。
我正在尝试连接 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'
。
这是怎么回事?
IIUC,您可以像这样连接您的列:
df.astype(str).sum(axis=1)
0 2a
1 1b
2 3c
3 4d
dtype: object
这会将所有列转换为类型 str
(df.astype(str)
),然后使用 sum
按行连接 (axis=1
)
使用
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
format_map
In [124]: df.apply('{A}{B}'.format_map, axis=1)
Out[124]:
0 2a
1 1b
2 3c
3 4d
dtype: object
如果您对性能感兴趣,请使用 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
由于 pandas 处理字符串的效率低下,相对而言,这将是一个非常快速的选择。