【问题标题】:When dtype is specified with genfromtxt a 2D array becomes 1D - how to prevent this?当使用 genfromtxt 指定 dtype 时,2D 数组变为 1D - 如何防止这种情况?
【发布时间】:2013-12-25 10:25:07
【问题描述】:

如下所示:

http://library.isr.ist.utl.pt/docs/numpy/user/basics.io.genfromtxt.html#choosing-the-data-type

“在除第一种情况之外的所有情况下,输出将是具有结构化 dtype 的一维数组。此 dtype 具有与序列中的项目一样多的字段。字段名称使用 names 关键字定义。”

问题是我该如何解决这个问题?我想将 genfromtxt 与具有列的数据文件一起使用,例如整数,字符串,整数。

如果我这样做:

dtype=(int, "|S5|", int)

然后整个形状从 (x, y) 变为仅 (x, ) 并且当我尝试使用掩码时出现“索引过多”错误。

当我使用 dtype=None 时,我可以保留 2D 结构,但如果第一行的列看起来可能是一个数字,它经常会出错(这经常发生在我的数据集中)。

我怎样才能最好地解决这个问题?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    你不能有一个二维数组,这意味着每行都有一个混合数据类型的一维数组,这是不可能的。

    拥有一组记录应该不是问题:

    In [1]: import numpy as np
    
    In [2]: !cat test.txt
    42 foo 41
    40 bar 39
    
    In [3]: data = np.genfromtxt('test.txt',
        ..:     dtype=np.dtype([('f1', int), ('f2', np.str_, 5), ('f3', int)]))
    
    In [4]: data
    Out[4]:
    array([(42, 'foo', 41), (40, 'bar', 39)],
          dtype=[('f1', '<i8'), ('f2', '<U5'), ('f3', '<i8')])
    
    In [5]: data['f3']
    Out[5]: array([41, 39])
    
    In [6]: data['f3'][1]
    Out[6]: 39
    

    如果您需要掩码数组,请看这里:How can I mask elements of a record array in Numpy?

    按第一列值屏蔽:

    In [7]: data['f1'] == 40
    Out[7]: array([False,  True], dtype=bool)
    
    In [8]: data[data['f1'] == 40]
    Out[8]:
    array([(40, 'bar', 39)],
          dtype=[('f1', '<i8'), ('f2', '<U5'), ('f3', '<i8')])
    

    【讨论】:

    • 我明白了,这是一个有趣的方法,谢谢。是否可以在此设置中以类似的方式使用掩码?对于二维数组,我做了类似 mask_column1 = data[:,0] == 'some value'; print(data[mask_column1]) - 当然这会报错。
    • @James 如果我明白你的意思,编辑应该显示一个例子
    猜你喜欢
    • 2020-08-10
    • 2018-10-16
    • 2023-04-03
    • 2021-12-30
    • 2023-03-04
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多