1

I am trying to conduct logical slicing on two lists and then concatenate them together while maintaining the original indicies.

Here is what I currently have:

x = np.array([0,12,2,246,13,42,245,235,26,33,235,236,23])
y = np.array([2,2,52,626,143,42,246,2,2,53,35,26,263])

r_1 = x<=y
r_2 = y<x

r = np.concatenate((x[r_1],y[r_2]))

This yields the following list:

[  0   2 246  13  42 245  33  23   2   2   2  35  26]

Instead, I would like it to go index by index and populate the lower value. The ideal list would be:

[0,2,2,246,13,42,245,2,2,26,33,26,23]

I know this can be done with a for loop, but I'll be doing this over thousands of data points making numpy a desirable option.

Any suggestions?

Thank you!

manninosi
  • 13
  • 4

2 Answers2

0

Just use np.min([x,y], axis=0)

mathfux
  • 5,759
  • 1
  • 14
  • 34
0

As mathfux just said, np.min([x,y], axis=0) will works perfectly for your problem.

But just in case you need to perform more complex logical operations, have a look at my solution that is slightly less efficient but easily customisable ;)

x = np.array([0,12,2,246,13,42,245,235,26,33,235,236,23])
y = np.array([2,2,52,626,143,42,246,2,2,53,35,26,263])

r_1 = x<=y
r_2 = y<x

r = np.zeros_like(x)
r[r_1] = x[r_1]
r[r_2] = y[r_2]
yannvm
  • 418
  • 1
  • 4
  • 12
  • Awesome! I think this should work for my case. I realize now my situation is a little more complex. I split values from array x into two arrays, one with them being >0 and the other <0. Each of those arrays are fed into a function to produce arrays that are the same length . I want to concatenate the resulting arrays with the indices being the same from the original logical slice. I think the zeros_like array addresses this situation. – manninosi Nov 21 '21 at 21:33