简体   繁体   English

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

[英]How to read text file with two related data sets using Python

I need to parse a fixed width text file which contains weather station's data in this format:我需要解析一个固定宽度的文本文件,其中包含以下格式的气象站数据:

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 rows : These rows starts with '#' and contain metadata information about the weather station and a field which tells us how many data lines to read under this header. header 行:这些行以“#”开头,包含有关气象站的元数据信息和一个字段,告诉我们在这个 header 下要读取多少数据行。

Data rows : The data rows contain the actual detailed weather data related to the header present above it.数据行:数据行包含与其上方显示的 header 相关的实际详细天气数据。

Sample :样本

# 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

As we can see, the header rows contain an indicator of how many data rows below are related to it正如我们所看到的,header 行包含一个指示器,指示下面有多少数据行与其相关

I want to create a dataframe or table such that I can have this consolidated data which looks something like this:我想创建一个 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
.
.

please suggest how to go about it.请建议如何到go一下。

You can first process the text file and split each rows into a list of their content, then append them into a list as you desire.您可以首先处理文本文件并将每一行拆分为它们的内容列表,然后 append 将它们放入您想要的列表中。 From there, you can create the dataframe into your desired output:从那里,您可以将 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM