Home > other >  Formatting a Numpy array with even and odd numbers
Formatting a Numpy array with even and odd numbers

Time:01-16

I am trying to write a code that replaces the even numbers with positive init_val value within the sequence_numbers and every odd and 0 valued variable into negative init_val values. How would I be able to code such a thing?

Code:

import numpy as np 
import pandas as pd 

sequence_numbers= np.array([1,0,4,7,9,12,15,16,22,2,4,8,11,13,11,21,23,3])

#The choice could be 'even', 'odd' or '0'
choice = 'even'
init_val = 100 

Expected output:

[-100, -100, 100, -100, -100, 100, -100,100, 100,
 100, 100, 100, -100, -100, -100, -100,  -100, -100 ]   

CodePudding user response:

Use numpy.where and the modulo operator to determine the odd/even status.

Example for 'even':

out = np.where(sequence_numbers%2, -init_val, init_val)

output:

array([-100,  100,  100, -100, -100,  100, -100,  100,  100,  100,  100,
        100, -100, -100, -100, -100, -100, -100])

For 'odd', just reverse the True/False values:

out = np.where(sequence_numbers%2, init_val, -init_val)

or inverse the init_val:

if choice == 'odd':
    init_val *= -1
out = np.where(sequence_numbers%2, -init_val, init_val)

CodePudding user response:

You can use:

out = (sequence_numbers % 2 * -2   1) * init_val
print(out)

# Output
array([-100,  100,  100, -100, -100,  100, -100,  100,  100,  100,  100,
        100, -100, -100, -100, -100, -100, -100])
  •  Tags:  
  • Related