+ 1

Numpy Slice by Value. There Has to be a Better Way!!!

I am trying to slice an array by the value it contains rather than it’s index. Basically I need to cut off everything after the last value in an array that is below a certain number and everything up to the first value that is above a certain certain number. The code can be written as: _____________________________________ Idx = range(np.min(np.where(y > 1.)), np.max(np.where(y < 6.))) _____________________________________ Here is some code that does that. The slice function does the slicing and I think it is too big and complicated. Its only in a function so I can test other options with the three test cases(in the dictionary) I couldn’t add a photo but if you go to my posts I posted a photo that shows what this line of code filters out of the dataset I am trying to work with. Is there a better way to do this??? Maybe in pandas? https://code.sololearn.com/cXIqhHHuH9gg/?ref=app

6th Mar 2021, 4:10 AM
Ethan
Ethan - avatar
4 ответов
+ 3
Ok I understand it a little better now. I came up with this, but I am not sure if it is more efficient or even completely correct for your use case. Maybe because I don't completely understand the characteristics of your function, how it can grow or shrink, and in which situation the tail has to be cropped. Maybe it would be useful to associate with each data point the direction (compared to the previous value) and make the decision based on that. Anyway, here is my try. https://code.sololearn.com/ca18a1340A02/?ref=app
28th Mar 2021, 4:01 PM
Tibor Santa
Tibor Santa - avatar
+ 2
You are probably overthinking this range / slice thing. Once you have a numpy array you can simply use math operators to retrieve indices where the condition applies. This gives a boolean array that you can use to slice the original data. For example condition = (y > 1.) & (y < 6.) See simple example https://code.sololearn.com/cA10A1165a2A/?ref=app
28th Mar 2021, 1:33 PM
Tibor Santa
Tibor Santa - avatar
+ 1
this is awesome
28th Mar 2021, 4:29 PM
Ethan
Ethan - avatar
0
this isn’t quite what I am looking for. I need to make the cutoff for messy data so I need to cut at the last time the data is below the max, even though it has gone above the max before that point. I can’t link posts for some reason but if you go to my posts you can see a picture of the graph.
28th Mar 2021, 2:26 PM
Ethan
Ethan - avatar