Home > database >  Combing and then maintaining indicies after numpy Logical Slicing
Combing and then maintaining indicies after numpy Logical Slicing

Time:11-20

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!

CodePudding user response:

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

CodePudding user response:

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]
  • Related