Reputation: 522
I have initialized matrix:
M = np.array(((),()))
M has the shape of (2,0) now. I wish to fill M by steps: firstly to add 1 number like
M[0] = np.append(M[0],55)
By this operation I want to get such a matrix
((55),())
How can I do this? I can make this with standard pythons arrays [] by "append" operation like
arr = [[],[]]
arr[0].append(55)
But after that, I need this array to be a numpy array and there is one extra type transform operation which I wish to avoid.
Upvotes: 0
Views: 847
Reputation: 231335
I can start with a 2 element object dtype array:
In [351]: M = np.array((None,None))
In [352]: M.shape
Out[352]: (2,)
In [353]: M
Out[353]: array([None, None], dtype=object)
In [354]: M[0]=(5,)
In [355]: M[1]=()
In [356]: M
Out[356]: array([(5,), ()], dtype=object)
In [357]: print(M)
[(5,) ()]
Or more directly (from a list of tuples) (beware, sometimes this produces a error rather than object array).
In [362]: np.array([(55,),()])
Out[362]: array([(55,), ()], dtype=object)
But I don't see what it's good for. It would easier to construct a list of tuples:
In [359]: [(5,), ()]
Out[359]: [(5,), ()]
Do not try to use np.append
like the list append. It is just a clumsy front end to np.concatenate
.
M
as you create it is:
In [360]: M = np.array(((),()))
In [361]: M
Out[361]: array([], shape=(2, 0), dtype=float64)
It can't hold any elements. And you can't change the shape of the slots as you can with a list. In numpy
shape
and dtype
are significant.
You can specify object
dtype:
In [367]: M = np.array([(),()], object)
In [368]: M
Out[368]: array([], shape=(2, 0), dtype=object)
but it's still impossible to reference and change one of those 0 elements.
Upvotes: 1
Reputation: 3928
The array you've written is no matrix because its axis has different dimensions. You could do it like this
import numpy as np
x = np.zeros((2,1))
x[0][0] = 55
Then if you want to append to it you can do something like:
x = np.append(x, [[42], [0]], axis=1)
Note that in order to append to a martrix all the dimensions except for the concatenation axis must match exactly
Upvotes: 1