The Wayback Machine - https://web.archive.org/web/20241007050704/https://www.geeksforgeeks.org/python-change-column-names-and-row-indexes-in-pandas-dataframe/
Open In App

Change column names and row indexes in Pandas DataFrame

Last Updated : 31 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Pandas DataFrame, let’s see how to change its column names and row indexes.

About Pandas DataFrame

Pandas 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 contains data for some specific attribute/variable.
  • Each dataframe column has a homogeneous data throughout any specific column but dataframe rows can contain homogeneous or heterogeneous data throughout any specific row.
  • Unlike two dimensional array, pandas dataframe axes are labeled.

Pandas Dataframe type has two attributes called ‘columns’ and ‘index’ which can be used to change the column names as well as the row indexes.

Create a DataFrame using dictionary.

Python3




# first import the libraries
import pandas as pd
 
# Create a dataFrame using dictionary
df=pd.DataFrame({"Name":['Tom','Nick','John','Peter'],
                "Age":[15,26,17,28]})
 
# Creates a dataFrame with
# 2 columns and 4 rows
df


Output:

    Name  Age
0 Tom 15
1 Nick 26
2 John 17
3 Peter 28

Method #1: Using df.columns and df.index

Changing the column name and row index using df.columns and df.index attribute. In order to change the column names, we provide a Python list containing the names of the column df.columns= ['First_col', 'Second_col', 'Third_col', .....]. In order to change the row indexes, we also provide a Python list for it df.index=['row1', 'row2', 'row3', ......].

Python3

# Let's rename already created dataFrame.

# Check the current column names
# using "columns" attribute.
# df.columns

# Change the column names
df.columns =['Col_1', 'Col_2']

# Change the row indexes
df.index = ['Row_1', 'Row_2', 'Row_3', 'Row_4']

# printing the data frame
print(df)

Output:

       Col_1  Col_2
Row_1 Tom 15
Row_2 Nick 26
Row_3 John 17
Row_4 Peter 28

Method #2: Using rename() function with dictionary

Let’s use the pandas rename function to change a single column.

Python3

# We can change multiple column names by
# passing a dictionary of old names and
# new names, to the rename() function.
df = df.rename({"Mod_col":"Col_1","B":"Col_2"}, axis='columns')

print(df)

Output:

       Col_1  Col_2
Row_1 Tom 15
Row_2 Nick 26
Row_3 John 17
Row_4 Peter 28

Change multiple column names simultaneously

Python3




# We can change multiple column names by
# passing a dictionary of old names and
# new names, to the rename() function.
df = df.rename({"Mod_col":"Col_1","B":"Col_2"}, axis='columns')
 
print(df)


Output:

       Col_1  Col_2
Row_1 Tom 15
Row_2 Nick 26
Row_3 John 17
Row_4 Peter 28

Method #3: Using Lambda Function to rename the columns

A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. Using the lambda function we can modify all of the column names at once. Let’s add ‘x’ at the end of each column name using lambda function

Python3

df = df.rename(columns=lambda x: x+'x')

# this will modify all the column names
print(df)

Output:

      Col_1x  Col_2x
Row_1 Tom 15
Row_2 Nick 26
Row_3 John 17
Row_4 Peter 28

Method #4: Using values attribute to rename the columns.

We can use the values attribute directly on the column whose name we want to change.

Python3

df.columns.values[1] = 'Student_Age'

# this will modify the name of the first column
print(df)

Output:

    Name  Student_Age
0 Tom 15
1 Nick 26
2 John 17
3 Peter 28

Let’s change the row index using the Lambda function.

Python3




# To change the row indexes
df = pd.DataFrame({"A":['Tom','Nick','John','Peter'],
                "B":[25,16,27,18]})
 
# this will increase the row index value by 10 for each row
df = df.rename(index = lambda x: x + 10)
 
print(df)


Output:

        A   B
10 Tom 25
11 Nick 16
12 John 27
13 Peter 18

Now, if we want to change the row indexes and column names simultaneously, then it can be achieved using

rename()

function and passing both column and index attribute as the parameter.

Python3




df = df.rename(index = lambda x: x + 5,
            columns = lambda x: x +'x')
 
# increase all the row index label by value 5
# append a value 'x' at the end of each column name.
print(df)


Output:

       Ax  Bx
15 Tom 25
16 Nick 16
17 John 27
18 Peter 18



Previous Article
Next Article

Similar Reads

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
How to get column and row names in DataFrame?
While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names and columns names in order to perform certain operations. Note: For downloading the nba dataset used in the below examples Click Here Getting row names in Pandas dataframe First, let's create a simple dataframe with nba.csv C/C++ Code #
3 min read
How to change dataframe column names in PySpark ?
In this article, we are going to see how to change the column names in the pyspark data frame. Let's create a Dataframe for demonstration: C/C++ Code # Importing necessary libraries from pyspark.sql import SparkSession # Create a spark session spark = SparkSession.builder.appName('pyspark - example join').getOrCreate() # Create data in dataframe da
3 min read
Add column names to dataframe in Pandas
In this article, we are going to see how to add column names to a dataframe. Let us how to add names to DataFrame columns in Pandas. Add Column Names to Pandas DataframeBelow are the steps and methods by which we can add column names in the Pandas dataframe in Python: Creating the DataFrameLet's first create an example DataFrame for demonstration r
2 min read
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 given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 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
How to drop multiple column names given in a list from PySpark DataFrame ?
In this article, we are going to drop multiple columns given in the list in Pyspark dataframe in Python. For this, we will use the drop() function. This function is used to remove the value from dataframe. Syntax: dataframe.drop(*['column 1','column 2','column n']) Where, dataframe is the input dataframecolumn names are the columns passed through a
2 min read
How to get rows/index names in Pandas dataframe
While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names in order to perform some certain operations. Let's discuss how to get row names in Pandas dataframe. First, let's create a simple dataframe with nba.csv C/C++ Code # Import pandas package import pandas as pd # making data frame data = p
2 min read
Remove spaces from column names in Pandas
Removing spaces from column names in pandas is not very hard we easily remove spaces from column names in pandas using replace() function. We can also replace space with another character. Let's see the example of both one by one. Example 1: remove the space from column name Python Code # import pandas import pandas as pd # create data frame Data =
1 min read
Pandas - Remove special characters from column names
Let us see how to remove special characters like #, @, &, etc. from column names in the pandas data frame. Here we will use replace function for removing special character. Example 1: remove a special character from column names Python Code # import pandas import pandas as pd # create data frame Data = {'Name#': ['Mukul', 'Rohan', 'Mayank', 'Sh
1 min read
How to Get Column Names in Pandas
While analyzing the real datasets which are often very huge in size, we might need to get the pandas column names in order to perform some certain operations. Let's discuss how to get column names in the Pandas . Syntax to Get Column Names in Pandas # Get column names as an Index objectcolumn_names = df.columns Get Column Names in Pandas Get a list
3 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
How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
Select row with maximum and minimum value in Pandas dataframe
Let's see how can we select rows with maximum and minimum values in Pandas Dataframe with help of different examples using Python. Creating a Dataframe to select rows with max and min values in Dataframe C/C++ Code # importing pandas and numpy import pandas as pd import numpy as np # data of 2018 drivers world championship dict1 = {'Driver': ['Hami
2 min read
Select any row from a Dataframe using iloc[] and iat[] in Pandas
In this article, we will learn how to get the rows from a dataframe as a list, using the functions ilic[] and iat[]. There are multiple ways to do get the rows as a list from given dataframe. Let’s see them will the help of examples. Python Code import pandas as pd # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/20
2 min read
Set the First Column and Row as Index in Pandas
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 t
4 min read
Using Timedelta and Period to create DateTime based indexes in Pandas
Real life data often consists of date and time-based records. From weather data to measuring some other metrics in big organizations they often rely on associating the observed data with some timestamp for evaluating the performance over time. We have already discussed how to manipulate date and time in pandas, now let's see the concepts of Timesta
3 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
Add a row at top in pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can add a row at top in pandas DataFrame.Observe this dataset first. C/C++ Code # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforg
1 min read
Insert row at given position in Pandas Dataframe
Inserting a row in Pandas DataFrame is a very straight forward process and we have already discussed approaches in how insert rows at the start of the Dataframe. Now, let's discuss the ways in which we can insert a row at any position in the dataframe having integer based index.Solution #1 : There does not exist any in-built function in pandas whic
3 min read
Select any row from a Dataframe in Pandas | Python
In this article, we will learn how to get the rows from a dataframe as a list, without using the functions like ilic[]. There are multiple ways to do get the rows as a list from given dataframe. Let’s see them will the help of examples. # importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2
1 min read
Get the specified row value of a given Pandas DataFrame
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Now let's see how to get the specified row value of a given DataFrame. We shall be using loc[ ], iloc[ ], and [ ] for a data frame object to select rows and columns from our data frame. iloc[ ] is used to select
2 min read
How to append a list as a row to a Pandas DataFrame in Python?
Prerequisite: Pandas DataFrame In this article, We are going to see how to append a list as a row to a pandas dataframe in Python. It can be done in three ways: Using loc[]Using iloc[]Using append()Append list using loc[] methods Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame.
3 min read
Sort Dataframe according to row frequency in Pandas
In this article, we will discuss how to use count() and sort_values() in pandas. So the count in pandas counts the frequency of elements in the dataframe column and then sort sorts the dataframe according to element frequency. count(): This method will show you the number of values for each column in your DataFrame.sort_values(): This method helps
2 min read
How to search a value within a Pandas DataFrame row?
In this article, we will see how to search a value within Pandas DataFrame row in Python. Importing Libraries and Data Here we are going to import the required module and then read the data file as dataframe. The link to dataset used is here C/C++ Code # importing pandas as ps import pandas as pd # importing data using .read_csv() method df = pd.re
2 min read
How to Get First Row of Pandas DataFrame?
In this article, we will discuss how to get the first row of the Pandas Dataframe Get the First Row of Pandas using iloc[] This method is used to access the row by using row numbers. We can get the first row by using 0 indexes. Example 1: Python code to get the first row of the Dataframe by using the iloc[] function C/C++ Code # import pandas modul
4 min read
Convert PySpark Row List to Pandas DataFrame
In this article, we will convert a PySpark Row List to Pandas Data Frame. A Row object is defined as a single Row in a PySpark DataFrame. Thus, a Data Frame can be easily represented as a Python List of Row objects. Method 1 : Use createDataFrame() method and use toPandas() method Here is the syntax of the createDataFrame() method : Syntax : curren
4 min read
How to Reverse Row in Pandas DataFrame?
In this article, we will learn how to reverse a row in a pandas data frame using Python. With the help of Pandas, we can perform a reverse operation by using loc(), iloc(), reindex(), slicing, and indexing on a row of a data set. Creating Dataframe Let’s create a simple data frame with a dictionary, say column names are: ‘Income’, ‘Expenses’, ‘Prof
3 min read
How to add header row to a Pandas Dataframe?
A header necessarily stores the names or headings for each of the columns. It helps the user to identify the role of the respective column in the data frame. The top row containing column names is called the header row of the data frame. There are two approaches to add header row to a Pandas Dataframe in case the original dataframe doesn't have a h
4 min read