【问题标题】:Numpy data alignment when slicing切片时的 Numpy 数据对齐
【发布时间】:2013-05-26 15:59:51
【问题描述】:

我执行以下操作:

from numpy import genfromtxt

x = genfromtxt('foo.csv',delimiter=',',usecols=(0,1))

y = genfromtxt('foo.csv',delimiter=',',usecols=(2),dtype=str)

然后我输入:

x[y=='y1Out',0] # assume the set of "y" is 'y1Out' and 'y2Out'

该命令在“x”中打印所有“0 列”值,其关联的“y”值等于y1Out。这怎么可能?也就是说,numpy 如何跟踪“x”和“y”之间的对齐方式?我以为 numpy 没有数据对齐。

【问题讨论】:

    标签: python numpy alignment slice


    【解决方案1】:

    当您执行y == 'y10ut' 并且ydtype 字符串的数组时,numpy 返回一个布尔数组,其中满足条件的索引为y。例如:

    import numpy as np
    y = np.empty(10, dtype='S8')
    # populating the array with 'y10ut' and 'y20ut' alternatively
    y[1::2] = 'y10ut'
    y[::2] = 'y20ut'
    

    然后你可以评估条件:

    >>> y == 'y10ut'
    array([False,  True, False,  True, False,  True, False,
           True, False,  True], dtype=bool)
    

    这个结果数组可以用作x 的索引数组。请注意,如果y 不是字符串数组,则生成的求值不再是索引数组:

    >>> y = np.arange(5, dtype='f')
    >>> y == 'y10ut'
    False
    

    在您的情况下,numpy 不知道 xy 之间的关系。但是给定条件y == 'y10ut',它会根据它索引x的第一个维度,这似乎是你想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2011-08-30
      • 1970-01-01
      相关资源
      最近更新 更多