2

I have a one dimensional array called Y_train that contains a series of 1's and 0's. I have another array called sample_weight that is an array of all 1's that has the shape of Y_train, defined as:

sample_weight = np.ones(Y_train.shape, dtype=int)

I'm trying to change the values in sample_weight to a 2, where the corresponding value in Y_train == 0. So initially side by side it looks like:

Y_train        sample_weight
0              1
0              1
1              1
1              1
0              1
1              1

and I'd like it to look like this after the transformation:

Y_train        sample_weight
0              2
0              2
1              1
1              1
0              2
1              1

What I tried was to use a for loop (shown below) but none of the 1's are changing to 2's in sample_weight. I'd like to somehow use the np.where() function if possible, but it's not crucial, just would like to avoid a for loop:

sample_weight = np.ones(Y_train.shape, dtype=int)
for num, i in enumerate(Y_train):
    if i == 0:
        sample_weight[num] == 2

I tried using the solution shown here but to no success with the second array. Any ideas??? Thanks!

1 Answer 1

2
import numpy as np

Y_train = np.array([0,0,1,1,0,1])
sample_weight = np.where(Y_train == 0, 2, Y_train)

>> print(sample_weight)
[2 2 1 1 2 1]

The np.where basically works just like Excel's "IF":

np.where(condition, then, else)

Works for transposed arrays, too:

Y_train = np.array([[0,0,1,1,0,1]]).T
sample_weight = np.where(Y_train == 0, 2, Y_train)

>> print(sample_weight)
[[2]
 [2]
 [1]
 [1]
 [2]
 [1]]
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm, and thank you for the quick lesson on where(). I learned proper syntax now. Thanks!

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.