[英]How to read text file with two related data sets using Python
我需要解析一个固定宽度的文本文件,其中包含以下格式的气象站数据:
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
.
header 行:这些行以“#”开头,包含有关气象站的元数据信息和一个字段,告诉我们在这个 header 下要读取多少数据行。
数据行:数据行包含与其上方显示的 header 相关的实际详细天气数据。
样本:
# 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
正如我们所看到的,header 行包含一个指示器,指示下面有多少数据行与其相关
我想创建一个 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
.
.
请建议如何到go一下。
您可以首先处理文本文件并将每一行拆分为它们的内容列表,然后 append 将它们放入您想要的列表中。 从那里,您可以将 dataframe 创建为您想要的 output:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.