
- Python Pandas - Home
- Python Pandas - Introduction
- Python Pandas - Environment Setup
- Python Pandas - Basics
- Python Pandas - Introduction to Data Structures
- Python Pandas - Index Objects
- Python Pandas - Panel
- Python Pandas - Basic Functionality
- Python Pandas - Indexing & Selecting Data
- Python Pandas - Series
- Python Pandas - Series
- Python Pandas - Slicing a Series Object
- Python Pandas - Attributes of a Series Object
- Python Pandas - Arithmetic Operations on Series Object
- Python Pandas - Converting Series to Other Objects
- Python Pandas - DataFrame
- Python Pandas - DataFrame
- Python Pandas - Accessing DataFrame
- Python Pandas - Slicing a DataFrame Object
- Python Pandas - Modifying DataFrame
- Python Pandas - Removing Rows from a DataFrame
- Python Pandas - Arithmetic Operations on DataFrame
- Python Pandas - IO Tools
- Python Pandas - IO Tools
- Python Pandas - Working with CSV Format
- Python Pandas - Reading & Writing JSON Files
- Python Pandas - Reading Data from an Excel File
- Python Pandas - Writing Data to Excel Files
- Python Pandas - Working with HTML Data
- Python Pandas - Clipboard
- Python Pandas - Working with HDF5 Format
- Python Pandas - Comparison with SQL
- Python Pandas - Data Handling
- Python Pandas - Sorting
- Python Pandas - Reindexing
- Python Pandas - Iteration
- Python Pandas - Concatenation
- Python Pandas - Statistical Functions
- Python Pandas - Descriptive Statistics
- Python Pandas - Working with Text Data
- Python Pandas - Function Application
- Python Pandas - Options & Customization
- Python Pandas - Window Functions
- Python Pandas - Aggregations
- Python Pandas - Merging/Joining
- Python Pandas - MultiIndex
- Python Pandas - Basics of MultiIndex
- Python Pandas - Indexing with MultiIndex
- Python Pandas - Advanced Reindexing with MultiIndex
- Python Pandas - Renaming MultiIndex Labels
- Python Pandas - Sorting a MultiIndex
- Python Pandas - Binary Operations
- Python Pandas - Binary Comparison Operations
- Python Pandas - Boolean Indexing
- Python Pandas - Boolean Masking
- Python Pandas - Data Reshaping & Pivoting
- Python Pandas - Pivoting
- Python Pandas - Stacking & Unstacking
- Python Pandas - Melting
- Python Pandas - Computing Dummy Variables
- Python Pandas - Categorical Data
- Python Pandas - Categorical Data
- Python Pandas - Ordering & Sorting Categorical Data
- Python Pandas - Comparing Categorical Data
- Python Pandas - Handling Missing Data
- Python Pandas - Missing Data
- Python Pandas - Filling Missing Data
- Python Pandas - Interpolation of Missing Values
- Python Pandas - Dropping Missing Data
- Python Pandas - Calculations with Missing Data
- Python Pandas - Handling Duplicates
- Python Pandas - Duplicated Data
- Python Pandas - Counting & Retrieving Unique Elements
- Python Pandas - Duplicated Labels
- Python Pandas - Grouping & Aggregation
- Python Pandas - GroupBy
- Python Pandas - Time-series Data
- Python Pandas - Date Functionality
- Python Pandas - Timedelta
- Python Pandas - Sparse Data Structures
- Python Pandas - Sparse Data
- Python Pandas - Visualization
- Python Pandas - Visualization
- Python Pandas - Additional Concepts
- Python Pandas - Caveats & Gotchas
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.
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 |
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.
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 |
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.
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 |
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.
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.
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.
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.
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 |