Skip to content
Advertisement

Conditional formatting of arrays in Numpy Python

I am trying to make a function where if the last value of order is 1 then the code will append 1 to orders and then append the number 20 to the value array as well. If the last value is 0 in order then it will append 1 to order and append the number 15 to value.

import numpy as np

order = np.array([0,1,0,0,0])
order1 = np.array([0,1,0,0,1])
value= np.array([10,55,30,3,10])

Expected Output:

#if last element is equal to 1 
order = np.array([0,1,0,0,0,1])
value= np.array([10,55,30,3,10,20])

#if last element is equal to 0 
order1 = np.array([0,1,0,0,1,0])
value= np.array([10,55,30,3,10,15])

Advertisement

Answer

def extend_order_and_value(order, value, order_0_extensors = (1, 20), order_1_extensors = (0, 15)):
    ## Return order and value extended by the values given in
    ## order_0_extensors or order_1_extensors depending on last order's value.
    ## the extensors have the form: (order_value, values_value) for the cases
    ## 0 or 1 as last value in order.
    
    # ensure that order and value are numpy arrays!
    order, value = np.array(order), np.array(value)
    
    if order[-1] == 0:
        order_val, value_val = order_0_extensors
    elif order[-1] == 1:
        order_val, values_val = order_1_extensors
    else:
        return order, value # return unchanged or raise error
    return np.concatenate([order, np.array([order_val])]), np.concatenate([values, np.array([values_val])])

Use it like this:

import numpy as np

order = np.array([0,1,0,0,0])
order1 = np.array([0,1,0,0,1])
value= np.array([10,55,30,3,10])


new_order, new_value = extend_order_and_value(order, value)                                                                
new_order
## array([0, 1, 0, 0, 0, 1])
new_value
## array([10, 55, 30,  3, 10, 20])

new_order1, new_value1 = extend_order_and_value(order1, value)                                                               
new_order1
## array([0, 1, 0, 0, 1, 0])
new_value1
## array([10, 55, 30,  3, 10, 15]))

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement