簡體   English   中英

使用 Python 從包含多組數據的文件中讀取指定列

[英]read specified column from a file which contains multiple sets of data using Python

我正在嘗試使用 python 從 .txt 文件加載多列數據。

我的文件包含多組數據,每組都有一個標題。

我想選擇一個集合,然后從中選擇 2 列。 我正在使用 genfromtxt 讀取 .txt 文件,但它將集合的標題作為列讀取,因此它給了我這種錯誤:

第 2 行(有 4 列而不是 1 列)

這是我的 txt 文件的示例,其中 TC_14TeV_NLO 和 TC_13TeV_LO 是標題,我想取每組的前 2 列:

TC_14TeV_NLO 
1000 1.51100e+01 6.2e-03 4.1e-02%
2000 7.36556e-01 4.4e-04 5.9e-02%
3000 7.85092e-02 5.1e-05 6.5e-02%
4000 1.17810e-02 7.4e-06 6.3e-02%
5000 2.39873e-03 1.3e-06 5.2e-02%
6000 7.18132e-04 2.7e-07 3.7e-02%
7000 3.10281e-04 8.1e-08 2.6e-02%
8000 1.67493e-04 3.3e-08 1.9e-02%
9000 1.01369e-04 2.2e-08 2.2e-02%
10000 6.54776e-05 1.6e-08 2.4e-02%

TC_13TeV_LO
1000 1.04906e+01 1.7e-03 1.7e-02%
2000 4.53170e-01 8.1e-05 1.8e-02%
3000 4.25722e-02 7.9e-06 1.9e-02%
4000 5.80036e-03 1.1e-06 1.9e-02%
5000 1.17278e-03 2.1e-07 1.8e-02%
6000 3.82330e-04 6.1e-08 1.6e-02%
7000 1.78036e-04 2.7e-08 1.5e-02%
8000 9.91945e-05 1.9e-08 1.9e-02%
9000 6.05766e-05 1.6e-08 2.6e-02%
10000 3.92631e-05 1.2e-08 3.0e-02%

對於您的示例文件,您可以執行以下操作:

import pandas as pd

#read in first set of data, start from the beginning, read 10 lines
df1=pd.read_csv('exfile.txt', sep=" ",skiprows=None,nrows=10)

#read in the second set of data, do not start at the beginning of file but skip 11 rows, read the next 10 lines
df2=pd.read_csv('exfile.txt', sep=" ",skiprows=11,nrows=10)

#choose any two cols, for example:
print(df1['TC'])
print(df2['13TeV'])

否則,我建議拆分為每個集合提供自己的文件,而不是使用 pandas.read_csv 讀取它們。

首先,定義一個函數來將文件拆分為多個部分。 這是一個生成器,它生成一系列行列表:

def split_sections(infile):
    """Generate a sequence of lists of lines from infile delimited by blank lines.
    """
    section = []
    for line in infile:
        if not line.strip():
            if section:
                yield section
                section = []
        else:
            section.append(line)
    if section: # last section may not have blank line after it
        yield section

那么你的實際任務相當簡單:

with open(path) as infile:
    for lines in split_sections(infile):
        heading = lines[0].rstrip()
        data = np.genfromtxt(lines[1:], usecols=[0,1])
        print(heading)
        print(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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