简体   繁体   中英

how to split array based on value in array?

Basically i have an array of data, and i want to split in into 2 based on the minima of the array. I tried a for loop, but it splits it based on the magnitude of the values, rather than, effectively, if its to the left or right of that value. I guess im looking for something effectively like the split module in numpy, but that returns 2 independent seperate arrays rather than an array with subarrays in it.

node1=[]
node2=[]
for i in profile_coarse:
    if i<7.2e-10: 
        node1.append(i)
    else:
        node2.append(i)

obviously because 7.2e-10 is the minima, all the values go to node2 and node1 remains an empty array. The minima is somewhere in the middle of my data array, and i want everything that comes before it to be stored in node1 and everything after in node2. i vaguely know what np.where is, but i cant seem to apply it correctly here. how can i alter the condition of the if loop such that it works? Thanks so much for the help!

EDIT: using the idea of the index of an array, i got here:

 node1=[]
 node2=[]
for index in enumerate(profile_coarse):
    if i<get_lowest_minima(profile_coarse)[0]:                        
        node1.append(i)
    else:
        node2.append(i)
print("array node1", node1, "array node2", node2)

which doesnt work - it fills the node1 array, and leaves node2 empty...i cant figure out why. teh get_lowest_minima(profile_coarse)[0] bit is an interger element of a tuple, and profile_coarse is the array of my data. help!

Here is a simple solution:

split_index = data.index(min(data))
data1 = data[:split_index]
data2 = data[split_index+1:]

You could also find the split_index with:

split_index = min(range(len(data)), key=data.__getitem__)

For more details check this question.

What you need is to find the index of the minimum value and then split the array based on that index.

import numpy as np


a = np.random.randint(0, 255, 10). # sample data [  9  33 155  48 196   3  96 185 112 104]

min_index = np.argmin(a)

node1 = a[:min_index]  # [  9  33 155  48 196]
node2 = a[min_index:]  # [  3  96 185 112 104]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM