NumPy genfromtxt - 列名

3

我试图使用genfromtxt导入一个简单的制表符分隔的文本文件。我需要访问每个列标题名称,以及与该名称相关联的列中的数据。目前,我正在以一种看起来有点奇怪的方式完成这个任务。文本文件中的所有值,包括标题,都是十进制数字。

sample input file:

1     2     3     4      # header row
1.2   5.3   2.8   9.5
3.1   4.5   1.1   6.7
1.2   5.3   2.8   9.5
3.1   4.5   1.1   6.7
1.2   5.3   2.8   9.5
3.1   4.5   1.1   6.7


table_data = np.genfromtxt(file_path)       #import file as numpy array
header_values = table_data[0,:]             # grab first row
table_values = np.delete(table_data,0,0)    # grab everything else

我知道导入文本数据文件的更好方式。我需要使每一列的标题和相关数据易于访问。感谢您提供的任何帮助。
澄清:
我想能够使用类似于table_values [header_of_first_column]的东西来访问数据列。我该如何实现这一点?

我认为没有其他方法可以获得您所需的内容,因为这是一个非常具体和不寻常的请求。您能做的最大化简最后一行。table_values = table_data[1:] - EnricoGiampieri
1个回答

5
使用 names参数 来将第一行有效数据作为列名:
data = np.genfromtxt(
    fname,
    names = True, #  If `names` is True, the field names are read from the first valid line
    comments = '#', # Skip characters after #
    delimiter = '\t', # tab separated values
    dtype = None)  # guess the dtype of each column

例如,如果我修改您发布的数据以确保其真正为制表符分隔,则以下代码将起作用:
import numpy as np
import os
fname = os.path.expanduser('~/test/data')
data = np.genfromtxt(
    fname,
    names = True, #  If `names` is True, the field names are read from the first valid line
    comments = '#', # Skip characters after #
    delimiter = '\t', # tab separated values
    dtype = None)  # guess the dtype of each column
print(data)
# [(1.2, 5.3, 2.8, 9.5) (3.1, 4.5, 1.1, 6.7) (1.2, 5.3, 2.8, 9.5)
#  (3.1, 4.5, 1.1, 6.7) (1.2, 5.3, 2.8, 9.5) (3.1, 4.5, 1.1, 6.7)]

print(data['1'])
# [ 1.2  3.1  1.2  3.1  1.2  3.1]

2
我在使用这个解决方案时遇到了问题。一些列标题包含小数点。但是,当它们被读取为名称时,它们会被替换为_或完全省略。我该如何纠正这个问题?例如: data.dtype.names将无法保留标题中的小数点。 - user1764386

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接