size of NumPy array

203,130

Solution 1

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

Solution 2

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Solution 3

[w,k] = a.shape will give you access to individual sizes if you want to use it for loops like in matlab

Share:
203,130

Related videos on Youtube

abalter
Author by

abalter

Updated on March 06, 2021

Comments

  • abalter
    abalter about 3 years

    Is there an equivalent to the MATLAB

     size()
    

    command in Numpy?

    In MATLAB,

    >>> a = zeros(2,5)
     0 0 0 0 0
     0 0 0 0 0
    >>> size(a)
     2 5
    

    In Python,

    >>> a = zeros((2,5))
    >>> 
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]])
    
    >>> ?????
    
    • Benjamin
      Benjamin almost 12 years
      Have a look at one of many such pages: scipy.org/NumPy_for_Matlab_Users
    • Ben Bolker
      Ben Bolker about 9 years
      I'm really curious why shape is an attribute of arrays and a function in the numpy model but not a method of array objects. Is there an obvious answer? Does it feel like it merits a separate SO question, or is it too potentially opinion-based?
    • Alex Strasser
      Alex Strasser about 5 years
      Here is the updated NumPy for Matlab Users link.
  • Guimoute
    Guimoute almost 6 years
    We can switch freely between np.method(x) and x.method when x is a numpy object?
  • Sven Marnach
    Sven Marnach almost 6 years
    @Guimoute It depends. First, shape isn't a method, it's a property. And for many methods there are corresponding module-level functions, but not for all of them. You need to consult the documentation for details.