首页 > 解决方案 > 如何从 pandas 的一个 TXT 文件中读取多个表?

问题描述

我有一个看起来像这样的文本文件,

data = '''1|b|c 
2|e|f|g|h|i|j|k
2|2|3|4|5|6|7|8
1|e|f'''

我想使用 pandas 从数据中创建多个表。

  1. 创建以 1 开头的行的表
  2. 创建以 2 开头的行的表

使用 pandas 完成此操作的推荐快速简便的方法是什么?

标签: pythonpandas

解决方案


您可以在pandas读取时设置分隔符,如下所示:

# Or .read_table
master_table = pd.read_csv("file.txt", delimter="|")

# Select just the rows where an arbitrary column is 1.
df1 = master_table[master_table["column_name"] == 1].copy()

也许遍历文件更简单:

with open("file.txt", "r") as file:
      for line in file:
           if line[0] == 1: # Check any arbitrary condition
               # Process the data

推荐阅读