1

There is a 1 dimensional numpy array named "target_y". My task is to ensure that "target_y" has all values encoded as 1 and -1, not 1 and 0 before performing logistic regression. Once I do it, I need to assign it to "prepared_y" and return it. Can I write something like:

if target_y in 1,-1:
    prepared_y = target_y 
S3DEV
  • 8,768
  • 3
  • 31
  • 42

4 Answers4

0

Checkout np.all:

We can do some quick boolean arithmetic to check if all the values are 1 or -1:

if np.all((target_y == 1) + (target_y == -1)): # checks if the array has all 1s and -1s
    prepared_y = target_y

If you want to change all 0s to -1s, slice for all 0s:

target_y[np.argwhere(target_y == 0)] = -1
M Z
  • 4,571
  • 2
  • 13
  • 27
0

For a List you can do:

def convert( l ):
  return [ -1 if e == 0 else e for e in l ]

For a numpy array

def convert( l ):
  return l[ l == 0 ] = -1
bicarlsen
  • 1,241
  • 10
  • 27
  • 1
    `[e or -1 for e in l]` – Olvin Roght Jan 09 '21 at 21:39
  • The reason I did it this way is in case there are other values than just `1` and `0`, but indeed, if you can ensure that those are the only two values @OlvinRoght's suggestion will work, defaulting to -1 if e evaluates to False. – bicarlsen Jan 09 '21 at 21:42
0

One value can be checked by if statement, such as:

if 0 in test_list:
    return test_list

To be exact to your answer, you need a loop to check each value:

def list_checker(test_list):
    for i, num in enumerate(test_list):
        if num == 0:
            test_list[i] = -1
    return test_list
Nitish
  • 392
  • 2
  • 7
0

To replace all 0 values with -1 in a numpy.array it’s as simple as:

a[a == 0] = -1

... where a is the 1 dimensional array.

S3DEV
  • 8,768
  • 3
  • 31
  • 42