The Wayback Machine - https://web.archive.org/web/20240807071908/https://www.geeksforgeeks.org/set-the-first-column-and-row-as-index-in-pandas/
Open In App

Set the First Column and Row as Index in Pandas

Last Updated : 02 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

In Pandas, an index is a label that uniquely identifies each row or column in a DataFrame. It serves as a reference or identifier for the data, allowing for easy and efficient data retrieval and manipulation. One common operation when working with tabular data is setting a specific column or row as the index. In this article, we will focus on how to set the first column and row as the index in a Pandas DataFrame.

Set the First Column and Row as Index in Pandas

Setting the First Column as the Index

Suppose we have a DataFrame with data as given below in Python

Python3




import pandas as pd
 
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'San Francisco', 'Los Angeles']}
df = pd.DataFrame(data)
 
print(df)


Output

      Name  Age           City
0 Alice 25 New York
1 Bob 30 San Francisco
2 Charlie 35 Los Angeles

To set the ‘Name’ column as the index, you can use the set_index method:

Python3




df.set_index('Name', inplace=True)
print(df)


Output

         Age           City
Name
Alice 25 New York
Bob 30 San Francisco
Charlie 35 Los Angeles

Setting the First Row as the Column Names

Suppose we have a DataFrame with data as given below.

Python3




import pandas as pd
 
data = [['Name', 'Age', 'City'],
        ['Alice', 25, 'New York'],
        ['Bob', 30, 'San Francisco'],
        ['Charlie', 35, 'Los Angeles']]
df = pd.DataFrame(data)
 
print(df)


Output

         0    1              2
0 Name Age City
1 Alice 25 New York
2 Bob 30 San Francisco
3 Charlie 35 Los Angeles

To set the first row as the column names, we can use the following code:

Python3




df.columns = df.iloc[0]
df = df[1:]
print(df)


Output

     Name  Age           City
1 Alice 25 New York
2 Bob 30 San Francisco
3 Charlie 35 Los Angeles

Setting both the row and column in a Pandas DataFrame

Suppose we have a DataFrame with data as given below.

Python3




import pandas as pd
 
data = [['Name', 'Alice', 'Bob', 'Charlie'],
        ['Age', 25, 30, 35],
        ['City', 'New York', 'San Francisco', 'Los Angeles']]
df = pd.DataFrame(data)
print(df)


Output

      0         1              2            3
0 Name Alice Bob Charlie
1 Age 25 30 35
2 City New York San Francisco Los Angeles

Now, let’s set the first row as column names and the first column as the index:

Python3




# Set the first row as column names
df.columns = df.iloc[0]
df = df[1:]
 
# Set the first column as the index
df.set_index('Name', inplace=True)
 
print(df)


Output

0        Alice            Bob      Charlie
Name
Age 25 30 35
City New York San Francisco Los Angeles

Set Index Using a List

In this example, we first create a DataFrame named df using sample data. We then define lists row_labels and col_labels that contain the labels we want to use for rows and columns, respectively. Finally, we set the index and column names of the DataFrame using these lists.

Python3




import pandas as pd
 
# Create a sample DataFrame
data = {'A': [1, 2, 3],
        'B': [4, 5, 6],
        'C': [7, 8, 9]}
 
df = pd.DataFrame(data)
 
# Define a list of row labels and column labels to use as the index
row_labels = ['Row1', 'Row2', 'Row3']
col_labels = ['ColA', 'ColB', 'ColC']
 
# Set the index using the lists
df.index = row_labels
df.columns = col_labels
 
# Display the DataFrame with the custom index
print(df)


Output

      ColA  ColB  ColC
Row1 1 4 7
Row2 2 5 8
Row3 3 6 9

Set Index Using a Range

In this example, we first create a DataFrame df using sample data. We then calculate the number of rows and columns in the DataFrame using the shape attribute. Next, we set the index using the range function to create a numeric range starting from 1.

Python3




import pandas as pd
import numpy as np
 
# Create a sample DataFrame
data = {'A': [1, 2, 3],
        'B': [4, 5, 6],
        'C': [7, 8, 9]}
 
df = pd.DataFrame(data)
 
# Define the number of rows and columns
num_rows = df.shape[0]
num_cols = df.shape[1]
 
# Set the index using a range of numbers
# Start from 1
df.index = range(1, num_rows + 1)
 
# Display the DataFrame with the numeric index
print(df)


Output

   A  B  C
1 1 4 7
2 2 5 8
3 3 6 9


Similar Reads

Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
Convert a column to row name/index in Pandas
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a column to row name/index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", "Pankaj", "Sumi
2 min read
How to Sort a Pandas DataFrame based on column names or row index?
Pandas dataframe.sort_index() method sorts objects by labels along the given axis. Basically, the sorting algorithm is applied to the axis labels rather than the actual data in the Dataframe and based on that the data is rearranged. Creating Pandas Dataframe Create a DataFrame object from the Python list of tuples with columns and indices, say colu
3 min read
Get column index from column name of a given Pandas DataFrame
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together. Syntax: DataFrame.columns Return: column names index Syntax: Index.get_loc(key, method=None, tolerance=None) Return: loc : int if unique index, slice if monotonic index, els
2 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
Change column names and row indexes in Pandas DataFrame
Given a Pandas DataFrame, let's see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns.Each row is a measurement of some instance while column is a vector which
4 min read
Multiply Each Value In A Column By A Row in Python Pandas
In Python Data Analysis and Manipulation, it's often necessary to perform element-wise operations between rows and columns of DataFrames. This article focuses on multiplying values in a column by those in a row, a task achievable using Pandas, NumPy, or even basic Python list comprehension. Understanding DataFrames and Multiplication OperationsData
3 min read
Determine Period Index and Column for DataFrame in Pandas
In Pandas to determine Period Index and Column for Data Frame, we will use the pandas.period_range() method. It is one of the general functions in Pandas that is used to return a fixed frequency PeriodIndex, with day (calendar) as the default frequency. Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None) Parameters:start : Left bound for
2 min read
How to Sort a Pandas DataFrame by Both Index and Column?
In this article, we will discuss how to sort a Pandas dataframe by both index and columns. Sort DataFrame based on IndexWe can sort a Pandas DataFrame based on Index and column using sort_index method. To sort the DataFrame based on the index we need to pass axis=0 as a parameter to sort_index method.To sort the DataFrame based on the column name t
3 min read
Minimize the absolute difference on path from first column to the last column
Given an integer matrix mat[][] with N rows and M columns. The task is to minimize the absolute difference between the maximum and minimum elements visited along the path from the first column to the last column. We can jump from the current column to any row in the next column. Note: We can start from first column (any row) and end at last column
8 min read
three90RightbarBannerImg