Efficient way to add a numpy array

I will keep it simple. I have a loop that adds a new line to a numpy array ... which is an efficient way to do this.

n=np.zeros([1,2])
for x in [[2,3],[4,5],[7,6]]
      n=np.append(n,x,axis=1)

Now the thing is that [0,0] adheres to this, so I have to remove it with

   del n[0]

Which seems silly ... So please tell me an effective way to do this.

   n=np.empty([1,2])

even worse, it creates an uninitialized value.

+4
source share
3 answers

A bit of technical explanation for the Why Lists part.

An internal problem for a list of unknown length is that it must somehow fit into the memory regardless of its length. There are two different possibilities:

  • ( , ..), .

  • . , , . , , . , .

, .. . Python # 2, " ". , , :

, append. , , .


, , , numpy.array numpy.empty (not numpy.zeros) , ndarray.resize .

- numpy.array(l) l , ( 100 000 000, 0,5 ).

:

numpy.empty + ndarray.resize, , .

+6

, :

data = [[2, 3], [4, 5], [7, 6]]
n = np.array(data)

, :

exp = np.array([2, 3])    

n = np.empty((3, 2))
for i in range(3):
    n[i, :] = i ** exp

, :

exp = np.array([2, 3])

n = []
i = np.random.random()
while i < .9:
    n.append(i ** exp)
    i = np.random.random()
n = np.array(n)

, n = np.empty((0, 2)), .

+5

You might want to try:

import numpy as np

n = np.reshape([], (0, 2))
for x in [[2,3],[4,5],[7,6]]:
      n = np.append(n, [x], axis=0)

Instead, np.appendyou can also use n = np.vstack([n,x]). I also agree with @Bi Rico that I will also use the list if you ndo not need to access it in a loop.

0
source

Source: https://habr.com/ru/post/1546192/


All Articles