简体   繁体   中英

Index elements from 2D array with a 2D array and change these elements according to a 1D array [Python]

to quantify the behaviour of a classifier I want to modify the input data and track the changes in classification. I am classifying 1D Signals and use algorithms that deliver explanations, that means another algorithm creates an array of the most important points for classification decision in the 1D signal. These most important point indices I then want to use to index the 1D Signal in the 2D array of Signals and modify the values at these points. The values for the modification have to come from an 1D array with random values, so that every signal gets changed with the same randomness. I will try to visualize it:

array_of_1D_Signals = [[8,1,2,8,3,4,8,1,3,8],[4,1,8,8,3,8,6,1,8,4],[...],[...]]
#examplary 4 most important points for every signal (lets randomly say the 8´s are important)
#they are ordered from most important to least important
list_of_indices_for_every_signal = [[7,3,0,9],[8,2,5,3],[...],[...]]
values_for_modification = [4,1,6,3]
#the array i need to create (the 8's get exchanged with the values )
modified_array_of_1D_Signals = [[6,1,2,1,3,4,4,1,3,3],[4,1,1,3,3,6,6,1,4,4],[...],[...]]

I have solved this with for loops, but i do this over millions of samples and it takes ages. Is there a smart numpy way of doing this? I have a little example version with fancy indexing.

array_of_1D_Signals = np.full((100,100),1,dtype ='float')
indices = np.random.randint(100,size = (100,100))
values = np.random.uniform(low = 0.0, high = 1.0, size=(100,))
rows = np.arange(start = 0 ,stop = array_of_1D_Signals.shape[0], step = 1)
rows = np.repeat(rows,4)
columns = indices[:,:4].flatten()
array_of_1D_Signals[rows,columns] = np.tile(values[:4],100)

But that doesnt feel the smartest way with the repeat of the rows and the tiling of the values, because I imagine it scales rather bad, because in my real analysis all dimension get big (millions of samples with thousands of points to change)

Maybe someone has an idea?

Thank you for your time

Ok, something I tried earlier and did wrong works, when done right. The solution is

np.put_along_axis(array_of_1D_Signals, indices[:,:4], values[:4], axis=1)

My first proposed solution also takes 2.3 times as long as this line of code. Hope this helps someone later.

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