python - 如何从 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 开头的行的表
- 创建以 2 开头的行的表
使用 pandas 完成此操作的推荐快速简便的方法是什么?
解决方案
您可以在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
推荐阅读
- javascript - 正则表达式 JS 在 JS 中没有输出
- javascript - 使用纯javascript循环嵌套对象数组时出错
- javascript - 在括号上的 JavaScript 中遇到问题
- java - 使用spring客户端删除RabbitMQ中的所有队列
- c# - Map MouseLeftButtonUp 并不总是触发
- html - 如何将按钮对齐到屏幕html的中心
- reactjs - 无服务器 lambda 函数无法与 CORS 反应
- flutter - 参数类型“Widget”不能分配给参数类型“PreferredSizeWidget?”。颤振中appBar发生错误
- angular - 在 Angular 中,如何在材质对话框模板中使用自定义验证器
- php - 如何从数组中隐藏数组索引号