Skip to main content
 首页 » 编程设计

python之在 pandas 中附加 txt 数据

2025年05月04日12youxin

我正在尝试从如下所示的 txt 文件中附加数据:

Kit Kat|2 packets |Candy| 6 
Flour|1 book|Book|2 

我正在尝试从这个 txt 文件创建一个 pandas DataFrame,其列名称为:name, quantity, category, ID。

这是我目前使用的代码:

import pandas as pd 
 
df = pd.DataFrame(columns=['Name', 'Quantity', 'Category', 'ID']) 
 
file = open("food.txt", "r") 
 
for line in file: 
   fields = line.split("|") 
   product = df.append({'Name': fields[0]}, ignore_index=True) 
   qty = df.append({'Quantity': fields[1]}, ignore_index=True) 
   category= df.append({'Category': fields[2]}, ignore_index=True) 
   ID = df.append({'ID': fields[3]}, ignore_index=True) 
 
df.head() 

结果我得到一个空数据框,有人知道为什么吗?

请您参考如下方法:

只需将 read_csv 与 sep='|' 和 names=[COLUMNS_NAME] 一起使用

import pandas as pd 
 
columns_name = ['Name', 'Quantity', 'Category', 'ID'] 
df = pd.read_csv('file.txt', sep='|', names=columns_name) 
 
print(df) 

文件.txt

Kit Kat|2 packets |Candy| 6 
Flour|1 book|Book|2 

结果: