Question

I'd like to perform a splice of sorts in NumPy. Let's say I have two arrays, a and b:

>>> a
array([[ 1, 10],
       [ 2, 20],
       [ 5, 30]])
>>> b
array([[ 1, 11],
       [ 3, 31],
       [ 4, 41]])

which I want to splice together into the following array, c:

>>> c
array([[  1.,  10.],
       [  2.,  20.],
       [  3.,  nan],
       [  4.,  nan],
       [  5.,  30.]])

That is, I splice the values from the first column of b into a without bothering about the second column.

I could of course implement this myself pretty easily, but it would be nicer to have NumPy do it for me instead. Is that possible?

Was it helpful?

Solution

The answer by mishaF is only missing the last step -- making the entries of the last column unique. The full code to get your c (except for the dtype, which changes from int to float in your post) is

b[:,1]=numpy.nan
c = numpy.r_[a, b]
c.sort(0)
c = c[numpy.unique(c[:,0], True)[1]]

OTHER TIPS

You could stack the two together and then sort. However, this doesn't take care of the fact that you have two occurrences of the index 1. Not sure this is a great improvement...

 b[:,1]=np.nan
 c = np.vstack((a,b))
 c.sort(0)

I don't think there is anything in NumPy to do that. Do you need exactly that result (in order, second column with undefined value)? Maybe there is something close that would still be useful for the end goal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top