How to extend an array in-place in Numpy?

后端 未结 4 988
南旧
南旧 2020-11-27 18:29

Currently, I have some code like this

import numpy as np
ret = np.array([])
for i in range(100000):
  tmp =  get_input(i)
  ret = np.append(ret, np.zeros(len         


        
4条回答
  •  隐瞒了意图╮
    2020-11-27 18:41

    You can use the .resize() method of ndarrays. It requires that the memory is not referred to by other arrays/variables.

    import numpy as np
    ret = np.array([])
    for i in range(100):
        tmp = np.random.rand(np.random.randint(1, 100))
        ret.resize(len(ret) + len(tmp)) # <- ret is not referred to by anything else,
                                        #    so this works
        ret[-len(tmp):] = tmp
    

    The efficiency can be improved by using the usual array memory overrallocation schemes.

提交回复
热议问题