python - 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'
。
到底是怎么回事?
解决方案
IIUC,您可以像这样连接您的列:
df.astype(str).sum(axis=1)
0 2a
1 1b
2 3c
3 4d
dtype: object
这会将所有列转换为类型str
( df.astype(str)
),然后用于sum
逐行连接 ( axis=1
)
推荐阅读
- scikit-learn - 在 sklearn 中的整个管道中保留或获取特征名称(XGBoost 特征重要性)
- php - 如何在 Laravel 8 的模板中使用不同的数据将单个电子邮件发送给多个收件人
- alpha-vantage - 来自 Alphavantage API 的股票分割信息
- sqlite - Microsoft.EntityFrameWork 中的 SQLite 加密
- reactjs - react-beautiful-dnd 中的“无法找到拖动手柄”错误
- java - 由于使用注释生成方法,如何抑制警告“无法解析方法”?
- java - 如何用一个单词结束while循环?
- javascript - 使用 Leaflet js php 可视化大型多边形数据集
- python - 从 Windows 上的 Python 列表中选择选项的对话框?
- r - 错误:“set_envvar”不是从“命名空间:xfun”导出的对象