Rebel
Rebel

Reputation: 515

How to match two arrays by adding NaNs to the smaller array?

I have to plot a set of arrays. However, the way I produce these arrays is meaningful. For example,

x = np.array([2, 4, 5])
y = np.array([14, 15, NaN, NaN, NaN, 16, NaN])

But I need to modify x into this format: np.array([2, 4, NaN, NaN, NaN, 5, NaN]) before being able to plot them. Since I have a considerable amount of such cases with the second array containing NaNs in arbitrary places, I would like to know what is the fastest way to convert x into y format by adding necessary NaNs.

thank you,

Upvotes: 1

Views: 888

Answers (2)

Chris
Chris

Reputation: 29742

One way using numpy.resize:

np.resize(x, y.shape[0])*(y/y)

Output:

array([ 2.,  4., nan, nan, nan,  5., nan])

Explanation:

  • numpy.resize: repeats input array (x) to match length of target y (i.e. y.shape[0])
  • y/y: yields 1 (int/int) or np.nan (anything/np.nan) to make a mapping array.
  • resized_arr * (y/y): Basically extract number from resized x where it can. Since multiplying any number with nan yields nan, this step makes sure that the final array has nan where necessary and otherwise grab from x.

Upvotes: 3

Lewis Morris
Lewis Morris

Reputation: 2134

How about this, not pretty but does the job.

def add_nans(x,y):
    lst = []
    index = 0
    for val in y:
        if np.isnan(val):
            lst.append(np.nan)
        else:
            lst.append(x[index])
            index +=1

    return np.array(lst)

x = np.array([2, 4, 5])
y = np.array([14, 15, NaN, NaN, NaN, 16, NaN])  

x_changed = add_nans(x,y)

Upvotes: 1

Related Questions