Numpy genfromtxt - column names



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

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]行的内容来访问一列数据。我该如何做到这一点?

使用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]

最新更新