【问题标题】:read specified column from a file which contains multiple sets of data using Python使用 Python 从包含多组数据的文件中读取指定列
【发布时间】:2018-09-01 08:13:45
【问题描述】:

我正在尝试使用 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%

【问题讨论】:

  • 为什么不把每个集合放到不同的文件中呢?我建议这样做,这样会更容易。
  • 确实,但我想知道如何处理这样的文件。

标签: python numpy genfromtxt


【解决方案1】:

对于您的示例文件,您可以这样做:

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 来读取它们。

【讨论】:

  • (另外,每个列的合适标题会使您的示例文件更好,标题缺少最后一列名称)
  • 感谢您的回答,朋友。我的想法是我有大量的集合,所以计数会太多。我在想一种方法让代码从标题中识别每个集合。标题不是 (TC 13TeV LO) 而是 (TC_13TeV_LO)。所以它不是列的标题,而是整个集合的标题。
【解决方案2】:

首先,定义一个函数来将文件分成多个部分。这是一个生成器,它产生一系列行列表:

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)

【讨论】:

  • 感谢约翰的回答。我已经尝试过您的代码,但仍然遇到相同的错误: ValueError: Some errors were detected !第 1 行(得到 1 列而不是 2 列)第 14 行(得到 1 列而不是 2 列)另一个想法是我有不同的标题(TC,SSM,NU,...),所以我必须做多个open() 作为 infile?
  • @Moe:我已经完全修改了我的答案,使其更加笼统并处理您询问的案例。我还在您的原始示例文本上进行了测试。
猜你喜欢
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
相关资源
最近更新 更多