我需要解析一个固定宽度的文本文件,其中包含气象站的数据,格式如下:
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
.
头行:这些行以“#”开头,并包含有关气象站的元数据信息和一个字段,该字段告诉我们要在此标题下读取多少行数据。
数据行:数据行包含与其上方的标题相关的实际详细天气数据。
样本
# 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或表,这样我就可以拥有这样的合并数据,如下所示:
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
.
.
请建议怎么做。
发布于 2022-04-14 19:43:08
您可以首先处理文本文件,然后将每一行拆分为它们的内容列表,然后根据需要将它们附加到列表中。在那里,您可以在所需的输出中创建dataframe:
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))
https://stackoverflow.com/questions/71876595
复制相似问题