Home » How to Insert a Row Into a Pandas DataFrame

How to Insert a Row Into a Pandas DataFrame

by Tutor Aspire

You can use the following basic syntax to insert a row into a a specific location in a pandas DataFrame:

import pandas as pd
import numpy as np

#insert row with values [1, 7, 6] into existing DataFrame at index=4
pd.DataFrame(np.insert(df.values, 4, values=[1, 7, 6], axis=0))

The following example shows how to use this syntax in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'B', 'B', 'C'],
                   'assists': [5, 7, 7, 9, 12],
                   'rebounds': [11, 8, 10, 6, 6]})

#view DataFrame
df

        team	assists	rebounds
0	A	5	11
1	A	7	8
2	B	7	10
3	B	9	6
4	C	12	6

Example 1: Insert Values Into First Row of Pandas DataFrame

We can use the following syntax to insert a row of values into the first row of a pandas DataFrame:

#insert values into first row of DataFrame
df2 = pd.DataFrame(np.insert(df.values, 0, values=['A', 3, 4], axis=0))

#define column names of DataFrame
df2.columns = df.columns

#view updated DataFrame
df2

	team	assists	rebounds
0	A	3	4
1	A	5	11
2	A	7	8
3	B	7	10
4	B	9	6
5	C	12	6

Example 2: Insert Values Into Specific Row of Pandas DataFrame

We can use the following syntax to insert a row of values into a specific row of a pandas DataFrame:

#insert values into third row (index position=2) of DataFrame
df2 = pd.DataFrame(np.insert(df.values, 2, values=['A', 3, 4], axis=0))

#define column names of DataFrame
df2.columns = df.columns

#view updated DataFrame
df2

        team	assists	rebounds
0	A	5	11
1	A	7	8
2	A	3	4
3	B	7	10
4	B	9	6
5	C	12	6

Example 3: Insert Values Into Last Row of Pandas DataFrame

We can use the following syntax to insert a row of values into the last row of a pandas DataFrame:

#insert values into last row of DataFrame
df2 = pd.DataFrame(np.insert(df.values, len(df.index), values=['A', 3, 4], axis=0))

#define column names of DataFrame
df2.columns = df.columns

#view updated DataFrame
df2

	team	assists	rebounds
0	A	5	11
1	A	7	8
2	B	7	10
3	B	9	6
4	C	12	6
5	A	3	4

Note: You can find the complete documentation for the NumPy insert() function here.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Insert a Column Into a Pandas DataFrame
How to Add Rows to a Pandas DataFrame

You may also like