Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

python - Overwriting numpy array in loop with appended elements

I have a number of numpy arrays which I would like to update. For each of them, I would like to append a copy of the first element at the end:

array_ = np.append(array_, array_[0])

Since there are a lot of them, a loop of some kind would be convenient. How can I perform this updating operation in a loop?

I have tried using something like

for array_ in [array_1, array_2, array_3]:
    array_ = np.append(array_, array_[0])

However, this does not overwrite the original array since array_ = ... does not treat it as a list. The solution from How to update multiple Numpy arrays in a loop (using array[:] = ...) does also not work, since the appended array has a different length.

I also tried converting to a list and other workarounds, but somehow I always find that at some point I have to make a copy such that the original array is not overwritten.

Can this be done in a way that overwrites the original arrays?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think that this is possible. Operations like numpy.append, concatenate etc always creates a copy of the numpy array and does not do the modifying operations in place. For example, you can maybe think of doing something like this -

import numpy as np

array_1 = np.random.rand(100)
array_2 = np.random.rand(100)
array_3 = np.random.rand(100)

arr_list = [array_1, array_2, array_3]
for i in range(len(arr_list)):
    arr_list[i] = np.append(arr_list[i], arr_list[i][0])

print(array_1.shape)

You are explicitly telling that you want the array stored in a specific index to be modified, but even in that case, the operations creates a new copy and simply stores the new reference to the list.

Now, if you could do the append operation in-place, something like this would work. But you can't, becasue how numpy operates.

In general, operations that changes the original size of the array can never be performed in-place. It always creates a new copy and assigns that to the variable in question. And I don't think that this can be done without modifying the array in place.

What I would suggest is not to have the variables array_i at all, store all the arrays only as a list. You wouldn't have this issue in that case.

(Having posted this, I am not sure if there is some weird way of doing this by directly assigning the output of a computation to specific ID or something, but I think it's much more convenient to have the entire thing stored as an array to start with)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...