2

I have an array data_set, size:(172800,3) and mask array, size (172800) consists of 1's and 0's. 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].

I have tried, "np.placed" function but here the problem is the incorrect size of mask array.

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.

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.

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]]
5
  • 1
    Try data_set[mask.astype(bool)] = 0 Commented Nov 3, 2019 at 15:45
  • Or data_set[np.where(mask)] = 0., data_set[mask == 1] = 0. Commented Nov 3, 2019 at 15:49
  • thank you. it works with [0,0,0] but what if i need to replace it with other values like ex. [128,16,128]? Commented Nov 3, 2019 at 15:50
  • 2
    data_set[mask.astype(bool)] = [128,16,128] Commented Nov 3, 2019 at 15:52
  • great! Thank you. Commented Nov 3, 2019 at 15:53

1 Answer 1

2

When you try to index your data with mask numpy assumes you are giving it a list of indices. Use boolean arrays, or convert your mask to a list of indices:

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.