簡體   English   中英

如何使用 Python 讀取包含兩個相關數據集的文本文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM