简体   繁体   English

如何根据掩码数组更改 numpy 数组?

[英]How to change numpy array based on mask array?

I have an array data_set, size:(172800,3) and mask array, size (172800) consists of 1's and 0's.我有一个数组 data_set,大小:(172800,3)和掩码数组,大小(172800)由 1 和 0 组成。 I would like to replace value form data_set array based on values (0 or 1) in mask array by the value defined by me: ex: [0,0,0] or [128,16,128].我想用我定义的值替换基于掩码数组中的值(0或1)的值形式data_set数组:例如:[0,0,0]或[128,16,128]。

I have tried, "np.placed" function but here the problem is the incorrect size of mask array.我试过“np.placed”function 但这里的问题是掩码数组的大小不正确。

I have also checked the more pythonic way: data_set[mask]= [0,0,0] it worked fine but for some raison only for 2 first elements.我还检查了更 Pythonic 的方式: data_set[mask]= [0,0,0] 它工作得很好,但是对于某些理由仅适用于 2 个第一个元素。

data_set[mask]= [0,0,0]

data_set = np.place(data_set, mask, [0,0,0])

My expected output is to change the value of element in data_set matrix to [0,0,0] if the mask value is 1.如果掩码值为 1,我预期的 output 是将 data_set 矩阵中元素的值更改为 [0,0,0]。

ex.前任。

data_set = [[134,123,90] , [234,45,65] , [32,233,45]]
mask = [ 1, 0, 1]

output = [[0,0,0] , [234, 45,65] , [0,0,0]]

When you try to index your data with mask numpy assumes you are giving it a list of indices.当您尝试使用mask numpy 为您的数据建立索引时,假设您正在给它一个索引列表。 Use boolean arrays, or convert your mask to a list of indices:使用 boolean arrays,或将掩码转换为索引列表:

import numpy as np

data_set = np.array([[134,123,90] , [234,45,65] , [32,233,45]])
mask = np.array([1, 0, 1])
val = np.zeros(data_set.shape[1])

data_set[mask.astype(bool),:] = val
# or
data_set[np.where(mask),:] = val

The first one converts your array of ints to an array of bools, while the second one creates a list of indexes where the mask is not zero.第一个将整数数组转换为布尔数组,而第二个创建掩码不为零的索引列表。

You can set val to whatever value you need as long as it matches the remaining dimension of the dataset (in this case, 3 ).您可以将val设置为您需要的任何值,只要它与数据集的剩余维度匹配(在本例中为3 )。

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

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