首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用Python读取包含两个相关数据集的文本文件

如何使用Python读取包含两个相关数据集的文本文件
EN

Stack Overflow用户
提问于 2022-04-14 19:13:27
回答 1查看 29关注 0票数 0

我需要解析一个固定宽度的文本文件,其中包含气象站的数据,格式如下:

代码语言:javascript
运行
复制
Header row (of particular width and columns)
Data row (of different fixed width and columns)
Data row
.
.
Header row
Data row
Data row
Data row
.
.
Header row
Data row
.

头行:这些行以“#”开头,并包含有关气象站的元数据信息和一个字段,该字段告诉我们要在此标题下读取多少行数据。

数据行:数据行包含与其上方的标题相关的实际详细天气数据。

样本

代码语言:javascript
运行
复制
# ID1 A1 B 2 C1
11 20
22 30
# ID2 A1 B 3 C2
23 45
10 17
43 12
# ID1 A3 B1 1 C2
21 32

正如我们所看到的,标题行包含一个指示符,指示下面有多少数据行与它相关。

我想要创建一个dataframe或表,这样我就可以拥有这样的合并数据,如下所示:

代码语言:javascript
运行
复制
ID1 A1 B 2 C1 11 20
ID1 A1 B 2 C1 22 30
ID2 A1 B 3 C2 23 45
ID2 A1 B 3 C2 10 17
.
.

请建议怎么做。

EN

回答 1

Stack Overflow用户

发布于 2022-04-14 19:43:08

您可以首先处理文本文件,然后将每一行拆分为它们的内容列表,然后根据需要将它们附加到列表中。在那里,您可以在所需的输出中创建dataframe:

代码语言:javascript
运行
复制
import pandas as pd

# Read the lines from the text file
with open('test.txt', 'r') as f:
    text_data = f.readlines()

data = [] # The list to append into
current_header = None # Placeholder for the header

# Iterate and fill the list
for row in text_data:
    # Track the current header row
    if row[0] == '#':
        current_header = row[1:].split()
    # Include the tracked header prefix to the row
    else:
        data.append(current_header + row.split())

# Your desired dataframe output
print(pd.DataFrame(data))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71876595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档