开发者

append versus resize for numpy array

开发者 https://www.devze.com 2023-01-01 05:18 出处:网络
I would like to append a value at the end of my numpy.array. I saw numpy.append function but this performs an exact copy of the original array adding at last my new value. I would like to avoid copies

I would like to append a value at the end of my numpy.array. I saw numpy.append function but this performs an exact copy of the original array adding at last my new value. I would like to avoid copies since my arrays are big.

I am using resize method and then set the last index available to the new value. Can you conf开发者_开发知识库irm that resize is the best way to append a value at the end? Is it not moving memory around someway?

oldSize = myArray,shape(0)
myArray.resize( oldSize + 1 )
myArray[oldSize] = newValue


My simple timing experiment of append vs. resizing showed that resizing is about 3x faster and its the fastest way that I can think of to do this. Also, the answer to this question seems to imply that resizing the array is the way to go because it is in-place.

Verdict: Use resize

P.S. You also might want to check out this discussion from a numpy mailing list.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号