【问题标题】:How to import same column name data with np.genfromtxt?如何使用 np.genfromtxt 导入相同的列名数据?
【发布时间】:2015-08-22 04:40:04
【问题描述】:

我在表格的文件 data.dat 中有数据:

column_1    col col col col col
1   2   3   1   2   3
4   3   2   3   2   4
1   4   3   1   4   3
5   6   4   5   6   4

我正在尝试使用 np.genfromtxt 导入,以便所有列名为 col 的数据都存储在变量 y 中。我用代码试了一下:

import numpy as np
data = np.genfromtxt('data.dat', comments='#', delimiter='\t', dtype=None, names=True).transpose()
y = data['col']

但它给了我以下错误:

ValueError: two fields with the same name

如何在 Python 中解决这个问题?

【问题讨论】:

  • 你使用的是哪个 numpy 版本?
  • 我使用的是 numpy 版本 1.9.2

标签: python numpy genfromtxt


【解决方案1】:

当您使用name=True 时,np.genfromtxt 返回一个structured array。请注意,data.dat 中标记为 col 的列与 col_n 形式的列名称消除歧义:

In [114]: arr = np.genfromtxt('data', comments='#', delimiter='\t', dtype=None, names=True)

In [115]: arr
Out[115]: 
array([(1, 2, 3, 1, 2, 3), (4, 3, 2, 3, 2, 4), (1, 4, 3, 1, 4, 3),
       (5, 6, 4, 5, 6, 4)], 
      dtype=[('column_1', '<i8'), ('col', '<i8'), ('col_1', '<i8'), ('col_2', '<i8'), ('col_3', '<i8'), ('col_4', '<i8')])

因此,一旦您使用names=True,选择与列名称col 关联的所有数据就变得更加困难。此外,结构化数组不允许您一次切片多个列。因此,将数据加载到同质 dtype 数组中会更方便(如果没有names=True,您会得到):

with open('data.dat', 'rb') as f:
    header = f.readline().strip().split('\t')
    arr = np.genfromtxt(f, comments='#', delimiter='\t', dtype=None)

然后你可以找到那些名称为col的列的数字索引:

idx = [i for i, col in enumerate(header) if col=='col']

并选择所有数据

y = arr[:, idx]

例如,

import numpy as np

with open('data.dat', 'rb') as f:
    header = f.readline().strip().split('\t')
    arr = np.genfromtxt(f, comments='#', delimiter='\t', dtype=None)
    idx = [i for i, col in enumerate(header) if col=='col']
    y = arr[:, idx]
    print(y)

产量

[[2 3 1 2 3]
 [3 2 3 2 4]
 [4 3 1 4 3]
 [6 4 5 6 4]]

如果你希望y 是一维的,你可以使用ravel()

print(y.ravel())

产量

[2 3 1 2 3 3 2 3 2 4 4 3 1 4 3 6 4 5 6 4]

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多