Pergunta

Olá, tenho uma série de dados de 1000 com 1500 pontos em cada um.

Eles formam uma matriz numpy (1000x1500) criada usando np.zeros ((1500, 1000)) e depois preenchida com os dados.

Agora, e se eu quiser que a matriz cresça para dizer 1600 x 1100? Eu tenho que adicionar matrizes usando hstack e vstack ou existe uma maneira melhor?

Eu gostaria que os dados já, na peça de 1000x1500 da matriz, não fossem alterados, apenas dados em branco (zeros) adicionados à parte inferior e à direita, basicamente.

Obrigado.

Foi útil?

Solução

If you want zeroes in the added elements, my_array.resize((1600, 1000)) should work. Note that this differs from numpy.resize(my_array, (1600, 1000)), in which previous lines are duplicated, which is probably not what you want.

Otherwise (for instance if you want to avoid initializing elements to zero, which could be unnecessary), you can indeed use hstack and vstack to add an array containing the new elements; numpy.concatenate() (see pydoc numpy.concatenate) should work too (it is just more general, as far as I understand).

In either case, I would guess that a new memory block has to be allocated in order to extend the array, and that all these methods take about the same time.

Outras dicas

This should do what you want (ie, using 3x3 array and 4x4 array to represent the two arrays in the OP)

>>> import numpy as NP
>>> a = NP.random.randint(0, 10, 9).reshape(3, 3)
>>> a
>>> array([[1, 2, 2],
           [7, 0, 7],
           [0, 3, 0]])

>>> b = NP.zeros((4, 4))

mapping a on to b:

>>> b[:3,:3] = a

>>> b
    array([[ 1.,  2.,  2.,  0.],
           [ 7.,  0.,  7.,  0.],
           [ 0.,  3.,  0.,  0.],
           [ 0.,  0.,  0.,  0.]])

No matter what, you'll be stuck reallocating a chunk of memory, so it doesn't really matter if you use arr.resize(), np.concatenate, hstack/vstack, etc. Note that if you're accumulating a lot of data sequentially, Python lists are usually more efficient.

You should use reshape() and/or resize() depending on your precise requirement.

If you want chapter and verse from the authors you are probably better off posting on the numpy discussion board.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top