如何扩展就地在numpy的数组? [英] How to extend an array in-place in Numpy?

查看:542
本文介绍了如何扩展就地在numpy的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一些codeS这样的

Currently, I have some codes 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(tmp)))
  ret = np.append(ret, np.ones(fixed_length))

我觉得这些codeS为效率不高 np.append 需要返回数组的副本,而不是修改RET就地

I think these codes are not efficient as np.append need to return a copy of the array instead of modify the ret in-place

我不知道我是否可以使用延长的numpy的数组是这样的:

I was wondering whether I can use the extend for a numpy array like this:

import numpy as np
from somewhere import np_extend
ret = np.array([])
for i in range(100000):
  tmp =  get_input(i)
  np_extend(ret, np.zeros(len(tmp)))
  np_extend(ret, np.ones(fixed_length))

,使延长会更高效。
有没有人有这个想法?
谢谢!

So that the extend would be much more efficient. Does anyone have ideas about this? Thanks!

推荐答案

想象一下,一个numpy的阵列占用的内存一个连续块中。现在设想其它的目的,说其他numpy的阵列,其占据的存储器只是我们numpy的阵列的左侧和右侧。会有无房可追加或扩大我们numpy的数组。在numpy的阵列中的相关数据始终占据着的连续的内存块。

Imagine a numpy array as occupying one contiguous block of memory. Now imagine other objects, say other numpy arrays, which are occupying the memory just to the left and right of our numpy array. There would be no room to append to or extend our numpy array. The underlying data in a numpy array always occupies a contiguous block of memory.

因此​​,任何请求追加到或扩展通过分配的内存了一个全新的较大的块,旧的数据复制到新的块,然后附加或扩展我们的numpy的阵列只能满足。

So any request to append to or extend our numpy array can only be satisfied by allocating a whole new larger block of memory, copying the old data into the new block and then appending or extending.

所以:


  1. 它不会就地发生。

  2. 这不会是有效的。

这篇关于如何扩展就地在numpy的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆