python - 如何在 Python 中将文本和数字转换为数据框?
问题描述
我有一个包含支出信息的文本文件。我想使用 pandas 和 Python 3 将文本转换为具有两列的数据框,而无需通过将相同的名称组合成一行并添加相应的数量以产生单个总数来重复行名。
原始“支出.txt:”
shaving 150
shaving 200
coffee 100
food 350
transport 60
transport 40
所需的输出数据帧:
CATEGORY TOTAL
shaving 350
coffee 100
food 350
transport 100
解决方案
这应该这样做:
df = pd.read_csv('spending.txt', header=None, sep='\s+')
df.columns = ['category', 'total']
df.groupby('category', as_index=False).sum()
category total
0 coffee 100
1 food 350
2 shaving 350
3 transport 100
推荐阅读
- excel - 索引匹配 与多个条件匹配
- html - 从 HTTP 迁移到 HTTPS
- ms-access - 通过复制现有表的结构创建 Access 表
- javascript - 连续加载localhost:3000
- reactjs - “错误:您试图在一个本应不可变且已被冻结的对象上设置键 `latitude` 的值为 `37.785834`。”
- node.js - 是否有任何功能可以为集合中的所有现有 mongodb 对象添加新属性
- javascript - 如何检查 Cloud Firestore 集合中的所有文档中是否存在字段值?
- java - Spring MVC 从 JSP 中的表单在 @Controller 中创建一个对象
- python - 使用 numpy 摆脱循环
- c# - 更新到 netcore3.0-preview8 后出现 Blazor Mono 客户端错误