使用列表推导替换m x n数组中的元素

时间:2018-08-16 21:58:49

标签: python arrays python-2.7 list-comprehension

我有一个数组:

a = array([[1,2,3,1], [2,5,3,1], [0,0,0,0], [5,3,2,5]])

我想基于每行的最后一项(0或1)来遍历数组。如果每行的最后一项为0,我想将该行中的其他3个项(仅)更改为np.nan。

例如:

a = array([[1,2,3,1], [2,5,3,1], [nan, nan, nan, 0], [5,3,2,5]])

我可以使用for循环来做到这一点。即:

for frames in range(len(a)):
    if a[frames][3] == 0:
        a[frames][0:2] = np.nan

有没有更有效的方法来使用列表理解功能?到目前为止,这就是我要提出的全部内容,但是感觉它可能会更加高效:

a = np.array([[np.nan, np.nan, np.nan] if frames[3] == 0 else frames[0:3] for frames in a])

这将创建一个数组数组,并裁剪最后一列

谢谢!

1 个答案:

答案 0 :(得分:2)

IIUC,您不需要列表理解。使用indexing

>>> a = np.array([[1,2,3,1], [2,5,3,1], [0,0,0,0], [5,3,2,5]], dtype=float)
>>> a[a[:,-1] == 0, 0:3] = np.nan

array([[  1.,   2.,   3.,   1.],
       [  2.,   5.,   3.,   1.],
       [ nan,  nan,  nan,   0.],
       [  5.,   3.,   2.,   5.]])

如果您有这些数组的字典,只需对每个数组进行索引

for a in data.values():
    a[a[:,-1] == 0, 0:3] = np.nan