How to Add Row Numbers to Dataframe in Python

To add row numbers to a dataframe in Python, you can use the reset_index() function or the range() function.

The following examples show how to add row numbers to a dataframe in Python.

Using reset_index() Function

We can use the reset_index() function to add row numbers to a dataframe.

Suppose we have the following dataframe:

# Import pandas library
import pandas as pd

# Define dataframe  
office_stuff = pd.DataFrame({
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
})

# Add row numbers
office_stuff.reset_index(inplace=True)

# Show dataframe
print(office_stuff)

Output: 👇️

   index        Date Product_Code Product_Name  Price  Status
0      0  01-03-2023        A-101       Laptop   4500       1
1      1  01-03-2023        A-102       Mobile    550       1
2      2  01-03-2023        A-103      Printer    250       1
3      3  01-03-2023        B-101     Keyboard     50       0
4      4  02-03-2023        B-102      Scanner    350       1
5      5  02-03-2023        B-104        Mouse     50       1

In this example, we use the reset_index() function to add row numbers to the dataframe, which can be seen in the index column.

Using range() Function

We can use the range() function to add row numbers to a dataframe.

Suppose we have the same dataframe as above.

We can use the following code to add row numbers to the dataframe:

# Add row numbers
office_stuff['Row_number'] = range(len(office_stuff))

# Show dataframe
print(office_stuff)

Output: 👇️

         Date Product_Code Product_Name  Price  Status  Row_number
0  01-03-2023        A-101       Laptop   4500       1           0
1  01-03-2023        A-102       Mobile    550       1           1
2  01-03-2023        A-103      Printer    250       1           2
3  01-03-3        B-101     Keyboard     50       0           3
4  02-03-2023        B-102      Scanner    350       1           4
5  02-03-2023        B-104        Mouse     50       1           5

In this example, we add a Row_number column to the dataframe, which contains the row number for each row.