简体   繁体   English

识别并替换ndarray中的行

[英]Identify and replace rows in a ndarray

This is similar to this question except I have a stricter condition: I need to replace a occurrences of an entire row and not just values that may exist elsewhere in the column. 除了我有一个更严格的条件外,这与问题类似:我需要替换整个行的出现,而不仅仅是替换列中其他地方可能存在的值。 The line #368 should give an idea of how many fancy-indexed experiments have thus far failed: 编号368的代码应该让您了解到目前为止有多少次花式索引的实验失败了:

In [368]:

a=np.array([[[ 42.30803907,   0.        ,   0.        ],
        [ 42.30803907,   3.0052592 ,   0.        ]],

       [[ 42.30803907,   3.0052592 ,   0.        ],
        [ 40.54907736,   5.44198582,   0.        ]],

       [[ 40.54907736,   5.44198582,   0.        ],
        [ 42.14713681,   8.84169967,   0.        ]]])
In [369]:

toBeReplaced=np.array([ 42.30803907,   3.0052592 ,   0.        ])
In [370]:

b=a==toBeReplaced
#b returns:
#array([[[ True, False,  True],
#        [ True,  True,  True]],
#
#       [[ True,  True,  True],
#        [False, False,  True]],
#
#       [[False, False,  True],
#        [False, False,  True]]], dtype=bool)

And here's where I can't seem to get the condition syntax right: 这是我似乎无法正确获取条件语法的地方:

a=np.where(b==[True,True,True], [9,9,9], a)

Out[373]:
array([[[  9.        ,   0.        ,   9.        ],
        [  9.        ,   9.        ,   9.        ]],

       [[  9.        ,   9.        ,   9.        ],
        [ 40.54907736,   5.44198582,   9.        ]],

       [[ 40.54907736,   5.44198582,   9.        ],
        [ 42.14713681,   8.84169967,   9.        ]]])

You can see that the boolean mask replaces all occurrences on a column basis. 您会看到布尔掩码会按列替换所有匹配项。 Is there a way to alter the Boolean mask or the array on which it is used as a selector so that only rows whose value in all three columns matches the columns of the search array? 有没有一种方法可以更改布尔型掩码或将其用作选择器的数组,以便仅其三列中的值都与搜索数组的列匹配的行?

(NB I should also note that although my data is float64, all the "matching" occurrences I'm looking for return True on np.all() as they are the same underlying computed value.) (注意,我还要注意,尽管我的数据是float64,但我正在寻找的所有“匹配”事件在np.all()上都返回True,因为它们是相同的基础计算值。)

You can create a mask identifying where the condition is satisfied in all the columns: 您可以创建一个掩码,以标识所有列中满足条件的位置:

mask = np.all(a==[42.30803907, 3.0052592, 0.], axis=2)
a[mask] = [9, 9, 9]

#array([[[ 42.30803907,   0.        ,   0.        ],
#        [  9.        ,   9.        ,   9.        ]],
# 
#       [[  9.        ,   9.        ,   9.        ],
#        [ 40.54907736,   5.44198582,   0.        ]],
# 
#       [[ 40.54907736,   5.44198582,   0.        ],
#        [ 42.14713681,   8.84169967,   0.        ]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM