首页 > 解决方案 > 如何在 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  

标签: pythonpandas

解决方案


这应该这样做:

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

推荐阅读