I want to create an array that initially has these values:
[[[0,0,0,0]], [[0,0,0,0]]]
Then appending zeros to the next row:
[[[0,0,0,0], [0,0,0,0]], [[0,0,0,0], [0,0,0,0]]]
and again similarly appending zeros to the next row in a loop:
[[[0,0,0,0], [0,0,0,0], ...], [[0,0,0,0], [0,0,0,0], ...]]
How can I do this with python? I tried
import numpy, pandas
x = numpy.array([[[0, 0, 0, 0]], [[0, 0, 0, 0]]])
numpy.append(x[0], [[0, 0, 0, 0]], axis=0)
print(x)
CodePudding user response:
What you're looking for might be numpy.insert(arr, obj, values, axis=None)
to "Insert values along the given axis before the given indices". In your case, in the array A (arr
) you want to insert zeros (values
) along axis 1 (axis=1
). If you want to insert the element at the beginning, specify the position 0 (obj
), but if you want it at the end use -1:
>>> A = np.array([[[0,0,0,0]], [[0,0,0,0]]])
>>> A.shape
(2, 1, 4)
>>> B = np.insert(A, 1, 0, axis=1)
>>> B.shape
(2, 2, 4)
CodePudding user response:
In [160]: x = numpy.array([[[0, 0, 0, 0]], [[0, 0, 0, 0]]])
In [161]: x
Out[161]:
array([[[0, 0, 0, 0]],
[[0, 0, 0, 0]]])
In [162]: x.shape
Out[162]: (2, 1, 4)
Let's be clear what you start with - note the shape!
Your append attempt:
In [163]: np.append(x[0], [[0, 0, 0, 0]], axis=0)
Out[163]:
array([[0, 0, 0, 0],
[0, 0, 0, 0]])
In [164]: _.shape
Out[164]: (2, 4)
It makes a NEW array - x[0]
is (1,4) array, and you join another (1,4) to make a (2,4). np.append
when used like this is just np.concatenate
. Read, and reread, the docs if necessary.
It did not change x
. np.append
is NOT a list append clone.
In [165]: x
Out[165]:
array([[[0, 0, 0, 0]],
[[0, 0, 0, 0]]])
If you must work incrementally, use list and list append. Arrays have a fixed size, so 'growing' them requires making a new array.