'How to get the the shape and the type of any object in Python

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.



Solution 1:[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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1