-1

I would like to know if there is a way to get the shape and the type of any variable in Python. In the IDE Spyder, there is a variable explorer that lists this information for all types of objects (numpy arrays, pandas dataframes, lists etc.) as you can see on this picture:

enter image description here

With shape and type I am referring to what you can actually see on the "Type" and "Size" column of Spyder.

I know that there are specific calls for the individual objects (like numpy and pandas) but I would like to know if there is also a way to get this information for any object type as it is done in Spyder. The solution mentioned here How do I determine the size of an object in Python? just gives the size of any object but not the shape that also includes information about the dimensionality.

PeterBe
  • 700
  • 1
  • 17
  • 37
  • Can you elaborate on what you mean by "shape" of an object? Its fields? – isaactfa May 09 '22 at 09:49
  • @isaactfa: Thanks for your comment. With shape and type I am referring to what you can actually see on the "Type" and "Size" column of Spyder. I updated the question. Thanks for the hint. – PeterBe May 09 '22 at 10:04
  • There is no single definition of "shape" for arbitrary objects. It looks like what you show uses the `len(…)` for builtin containers, the `….shape` for numpy/pandas containers, and 1 for non-containers – is that all you need to have covered? – MisterMiyagi May 09 '22 at 10:07
  • Thanks MisterMiyagi for your comment. Actually my question was targeting towards a command that is independant from the actual data type. I want to know it something like this is possible where I don't have to know in advance which datatype I am using. In Spyder the variable explorer does that so somehow it infers this information. – PeterBe May 09 '22 at 10:08

1 Answers1

1

To get type of any object use type():

For eg:

>>> type([1,2,3])
<class 'list'>
>>> type(np.array([1,3,4]))
<class 'numpy.ndarray'>
>>> df = pd.DataFrame()
>>> type(df)
<class 'pandas.core.frame.DataFrame'>

I don't think there's any function in Python that can tell you the shape of any object without knowing its datatype. What you can do is check for the data type of the object using type() and then use len() or np.shape or df.shape accordingly.

To get the shape of a list or a tuple which are (1-D) arrays use len():

>>> len([1,2,3])
3

Don't use len() for more than 1-D arrays because that will be wrong shape. Use numpy instead. Eg:

>>> len([[1,2,3], [4,5,6]])
2 # This is wrong

To get the shape of Numpy objects use np.shape(object) or object.shape. Make sure that the numpy library is imported. :

>>> np.shape([1,2,3]) 
(3,)
>>> np.array([1,2,3]).shape
(3,)

To get the shape of Pandas objects use .shape on the object. Make sure that the pandas library is imported. You need to use .shape on the object like df is an object so use df.shape:

>>> df.shape
(0, 0)
Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27