DEV Community

vindianadoan
vindianadoan

Posted on

A cheat sheet on Pandas DataFrame Attributes

This post summarises a range of commonly used attributes of a pandas DataFrame object.
Using this DataFrame as an example:

import pandas as pd 
df = pd.DataFrame({
    'name': ["A", "B"],
    'value': [1,2]
})
Enter fullscreen mode Exit fullscreen mode

1. Core Attributes

Attribute Description Output
.shape Returns a tuple representing the dimensionality of the DataFrame in the form (number_of_rows, number_of_columns). print(df.shape)
# Output: (2,2)
.columns Returns an Index object containing the column labels of the DataFrame print(df.columns)
# Output: Index(['name', 'value'], dtype='object')
.index Represents the row labels of the DataFrame, encapsulated in an Index object. print(df.index)
# Output: RangeIndex(start=0, stop=2, step=1)
.dtypes Provides the data type of each column in the DataFrame. print(df.dtypes)
# Output
name object
value int64
dtype: object

2. Data Inspection Attributes

Attribute Description Output
.values Returns a NumPy array representation of the DataFrame's data. print(df.values)
# Output:
[['A' 1]
['B' 2]]
.size Returns the total number of elements in the DataFrame (calculated as rows x columns). print(df.size)
# Output: 4
.ndim Returns the number of dimensions of the DataFrame. For DataFrames, this is always 2. print(df.ndim)
# Output: 2
.empty Returns True if the DataFrame is empty (ie. has no elements), otherwise False. print(pd.DataFrame().empty)
# Output: True

3. Others

Attribute Description Output
.T (Transpose) Returns the transpose of the DataFrame, swapping rows with columns. print(df.values)
name A B
value 1 2

Top comments (0)