How to update multiple Numpy arrays in a loop

送分小仙女□ 提交于 2021-01-29 20:41:13

问题


I would like to update (prepend each one with additional elements) many numpy arrays in a loop, without having to repeat the code for each one.

I tried creating a list of all the arrays and looping through the items in that list and updating each one, but that doesn't change the original array.

import numpy as np
arr01 = [1,2,3]
arr02 = [4,5,6]
arr99 = [7,8,9]
print('initial arr01', arr01)
arraylist = [arr01, arr02, arr99]
for array in arraylist:
    array = np.concatenate((np.zeros(3, dtype=int), array))
    print('array being modified inside the loop', array)
print('final arr01', arr01)

In the sample code, I expected arr01, arr02, arr03 to all be modified with the prepended zeros.


回答1:


array = np.concatenate((np.zeros(3, dtype=int), array)) does not change the current array but creates a new one and stores it inside the variable array. So for the solution you have to change the values of the array itself, which can be done with array[:].

That means the only change you would have to make is replacing this one line

array[:] = np.concatenate((np.zeros(3, dtype=int), array))

So your correct solution would be

import numpy as np
arr01 = [1,2,3]
arr02 = [4,5,6]
arr99 = [7,8,9]
print('initial arr01', arr01)
arraylist = [arr01, arr02, arr99]
for array in arraylist:
    array[:] = np.concatenate((np.zeros(3, dtype=int), array))
    print('array being modified inside the loop', array)
print('final arr01', arr01)


来源:https://stackoverflow.com/questions/57403239/how-to-update-multiple-numpy-arrays-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!