Python Pandas - Index Objects



In Pandas, Index Objects play an important role in organizing and accessing data in a structured way. They work like labeled arrays and play an important role in defining how data is arranged and accessed in structures like Series and DataFrames. The Index allows quick data searches, efficient slicing, and keeps data properly aligned, while giving each row meaningful labels.

An Index is used to label the rows of a DataFrame or elements in a Series. These labels can be numbers, strings, or dates, and they help you to identify the data. One key thing to remember about Pandas indexes is that they are immutable, meaning you cannot change their size once created.

In this tutorial, we will learn about Pandas Index Objects, and various types of indexes in pandas.

The Index Class

The Index class is a basic object for storing all index types in Pandas objects. It provides the basic functionality for accessing and manipulating data.

Key Features of Index Object

  • Immutable: Index object is a immutable sequence, which cannot modify once it is created.

  • Alignment: Index ensures that data from different DataFrames or Series can be combined correctly, based on the index values.

  • Slicing: Index allows fast slicing and retrieval of data based on labels.

Syntax

Following is the syntax of the Index class −

class pandas.Index(data=None, dtype=None, copy=False, name=None, tupleize_cols=True)

Where,

  • data: The data for the index, which can be an array-like structure (like a list or numpy array) or another index object.

  • dtype: It specifies the data type for the index values, If not provided, Pandas will decide the data type based on the index values.

  • copy: It is a boolean parameter (True or False), which, specifies to create a copy of the input data.

  • name: This parameter gives a label to the index.

  • data: It is also a boolean parameter (True or False), When True, it tries to create MultiIndex if possible.

Types of Indexes in Pandas

Pandas provides various types of indexes to handle different types of data. Such as −

Let's discuss about all types of indexes in pandas.

NumericIndex

A NumericIndex is the basic index type in Pandas, it contains numerical values. NumericIndex is a default index and Pandas automatically assigns this if you did not provided any index.

Example

Following example demonstrates how pandas automatically assigns NumericIndex to a pandas DataFrame object.

Open Compiler
import pandas as pd # Generate some data for DataFrame data = { 'Name': ['Steve', 'Lia', 'Vin', 'Katie'], 'Age': [32, 28, 45, 38], 'Gender': ['Male', 'Female', 'Male', 'Female'], 'Rating': [3.45, 4.6, 3.9, 2.78] } # Creating the DataFrame df = pd.DataFrame(data) # Display the DataFrame print(df) print("\nDataFrame Index Object Type:",df.index.dtype)

Following is the output of the above code −


Name Age Gender Rating
0 Steve 32 Male 3.45
1 Lia 28 Female 4.60
2 Vin 45 Male 3.90
3 Katie 38 Female 2.78
DataFrame Index Object Type: int64

Categorical Index

The CategoricalIndex is used to deal the duplicate labels. This index is efficient in terms of memory usage and handling the large number of duplicate elements.

Example

The Following example create a Pandas DataFrame with the CategoricalIndex.

Open Compiler
import pandas as pd # Creating a CategoricalIndex categories = pd.CategoricalIndex(['a','b', 'a', 'c']) df = pd.DataFrame({'Col1': [50, 70, 90, 60], 'Col2':[1, 3, 5, 8]}, index=categories) print("Input DataFrame:\n",df) print("\nDataFrame Index Object Type:",df.index.dtype)

Following is the output of the above code −

Input DataFrame:
Col1 Col2
a 50 1
b 70 3
a 90 5
c 60 8
DataFrame Index Object Type: category

IntervalIndex

An IntervalIndex is used to represent intervals (ranges) in your data. This type of index will be created using the interval_range() method.

Example

Following example creates a DataFrame with IntervalIndex using the interval_range() method.

Open Compiler
import pandas as pd # Creating a IntervalIndex interval_idx = pd.interval_range(start=0, end=4) # Creating a DataFrame with IntervalIndex df = pd.DataFrame({'Col1': [1, 2, 3, 4], 'Col2':[1, 3, 5, 8]}, index=interval_idx) print("Input DataFrame:\n",df) print("\nDataFrame Index Object Type:",df.index.dtype)

Following is the output of the above code −

Input DataFrame:
Col1 Col2
(0, 1] 1 1
(1, 2] 2 3
(2, 3] 3 5
(3, 4] 4 8
DataFrame Index Object Type: interval[int64, right]

MultiIndex

Pandas MultiIndex is used to represent multiple levels or layers in index of Pandas data structures, which is also called as hierarchical.

Example

The following example shows the creation of a simple MultiIndexed DataFrame.

Open Compiler
import pandas as pd # Create MultiIndex arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']] multi_idx = pd.MultiIndex.from_arrays(arrays, names=('number', 'color')) # Create a DataFrame with MultiIndex df = pd.DataFrame({'Col1': [1, 2, 3, 4], 'Col2':[1, 3, 5, 8]}, index=multi_idx) print("MultiIndexed DataFrame:\n",df)

Following is the output of the above code −

MultiIndexed DataFrame:
Col1 Col2
1 red 1 1
blue 2 3
2 red 3 5
blue 4 8

DatetimeIndex

Pandas DatetimeIndex object is used to represent the date and time values. Nothing but it used for time-series data where each row is linked to a specific timestamp.

Example

The Following example create a Pandas DataFrame with the DatetimeIndex.

Open Compiler
import pandas as pd # Create DatetimeIndex datetime_idx = pd.DatetimeIndex(["2020-01-01 10:00:00", "2020-02-01 11:00:00"]) # Create a DataFrame with DatetimeIndex df = pd.DataFrame({'Col1': [1, 2], 'Col2':[1, 3]}, index=datetime_idx ) print("DatetimeIndexed DataFrame:\n",df)

Following is the output of the above code −

DatetimeIndexed DataFrame:
Col1 Col2
2020-01-01 10:00:00 1 1
2020-02-01 11:00:00 2 3

TimedeltaIndex

Pandas TimedeltaIndex is used represent a duration between two dates or times, like the number of days or hours between events.

Example

This example creates a Pandas DataFrame with a TimedeltaIndex.

Open Compiler
import pandas as pd # Create TimedeltaIndex timedelta_idx = pd.TimedeltaIndex(['0 days', '1 days', '2 days']) # Create a DataFrame with TimedeltaIndex df = pd.DataFrame({'Col1': [1, 2, 3], 'Col2':[1, 3, 3]}, index=timedelta_idx ) print("TimedeltaIndexed DataFrame:\n",df)

Following is the output of the above code −

TimedeltaIndexed DataFrame:
Col1 Col2
0 days 1 1
1 days 2 3
2 days 3 3

PeriodIndex

Pandas PeriodIndex is used to represent regular periods in time, like quarters, months, or years.

Example

This example creates a Pandas DataFrame with PeriodIndex object.

Open Compiler
import pandas as pd # Create PeriodIndex period_idx = pd.PeriodIndex(year=[2020, 2024], quarter=[1, 3]) # Create a DataFrame with PeriodIndex df = pd.DataFrame({'Col1': [1, 2], 'Col2':[1, 3]}, index=period_idx ) print("PeriodIndexed DataFrame:\n",df)

Following is the output of the above code −

PeriodIndexed DataFrame:
Col1 Col2
2020Q1 1 1
2024Q3 2 3
Advertisements