Numpy.shape Gives Inconsistent Responses - Why?
Solution 1:
When you invoke the .shape
attribute of a ndarray
, you get a tuple with as many elements as dimensions of your array. The length, ie, the number of rows, is the first dimension (shape[0]
)
- You start with an array :
c=np.array([1,2])
. That's a plain 1D array, so its shape will be a 1-element tuple, andshape[0]
is the number of elements, soc.shape = (2,)
- Consider
c=np.array([[1,2]])
. That's a 2D array, with 1 row. The first and only row is[1,2]
, that gives us two columns. Therefore,c.shape=(1,2)
andlen(c)=1
- Consider
c=np.array([[1,],[2,]])
. Another 2D array, with 2 rows, 1 column:c.shape=(2,1)
andlen(c)=2
. - Consider
d=np.array([[1,],[2,]]).transpose()
: this array is the same asnp.array([[1,2]])
, therefore its shape is(1,2)
.
Another useful attribute is .size
: that's the number of elements across all dimensions, and you have for an array c
c.size = np.product(c.shape)
.
More information on the shape in the documentation.
Solution 2:
len(c.shape)
is the "depth" of the array.
For c
, the array is just a list (a vector), the depth is 1.
For d
, the array is a list of lists, the depth is 2.
Note:
c.transpose()
# array([1, 2])
which is not d
, so this behaviour is not inconsistent.
dt = d.transpose()
# array([[1],
# [2]])
dt.shape # (2,1)
Solution 3:
Quick Fix: check the .ndim property - if its 2, then the .shape property will work as you expect.
Reason Why: if the .ndim property is 2, then numpy reports a shape value that agrees with the convention. If the .ndim property is 1, then numpy just reports shape in a different way.
More talking: When you pass np.array a lists of lists, the .shape property will agree with standard notions of the dimensions of a matrix: (rows, columns).
If you pass np.array just a list, then numpy doesn't think it has a matrix on its hands, and reports the shape in a different way.
The question is: does numpy think it has a matrix, or does it think it has something else on its hands.
Solution 4:
transpose
does not change the number of dimensions of the array. If c.ndim == 1
, c.transpose() == c
. Try:
c = np.array([1,2])
print c.shape
print c.T.shape
c = np.atleast_2d(c)
print c.shape
print c.T.shape
Solution 5:
Coming from Matlab, I also find it difficult that a single-dimensional array is not organized as (row_count, colum_count)
My function had to respond consistently on a single-dimensional ndarray like [x1, x2, x3] or a list of arrays [[x1, x2, x3], [x1, x2, x3], [x1, x2, x3]].
This worked for me:
dim = np.shape(subtract_matrix)[-1]
Picking the last dimension.
Post a Comment for "Numpy.shape Gives Inconsistent Responses - Why?"