How to Add Rows to a Pandas DataFrame (With Examples)

Adding rows to a Pandas DataFrame is relatively simple. One way is to use the append function, which adds the rows of one DataFrame to the end of another. Another way is to use the concat function, which adds the rows of one DataFrame to the beginning or end of another. These methods can be used to add single or multiple rows at a time. Finally, the insert function can be used to insert a new row into a specific position within the DataFrame.


You can use the df.loc() function to add a row to the end of a pandas DataFrame:

#add row to end of DataFrame
df.loc[len(df.index)] = [value1, value2, value3, ...]

And you can use the df.append() function to append several rows of an existing DataFrame to the end of another DataFrame:

#append rows of df2 to end of existing DataFrame
df = df.append(df2, ignore_index = True)

The following examples show how to use these functions in practice.

Example 1: Add One Row to Pandas DataFrame

The following code shows how to add one row to the end of a pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18],
                   'rebounds': [7, 7, 8, 13, 7, 4],
                   'assists': [11, 8, 10, 6, 6, 5]})

#view DataFrame
df

	points	rebounds assists
0	10	7	 11
1	12	7	 8
2	12	8	 10
3	14	13	 6
4	13	7	 6
5	18	4	 5

#add new row to end of DataFrame
df.loc[len(df.index)] = [20, 7, 5]

#view updated DataFrame
df

        points	rebounds assists
0	10	7	 11
1	12	7	 8
2	12	8	 10
3	14	13	 6
4	13	7	 6
5	18	4	 5
6	20	7	 5

Example 2: Add Several Rows to Pandas DataFrame

The following code shows how to add several rows of an existing DataFrame to the end of another DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [10, 12, 12, 14, 13, 18],
                   'rebounds': [7, 7, 8, 13, 7, 4],
                   'assists': [11, 8, 10, 6, 6, 5]})

#view DataFrame
df

	points	rebounds assists
0	10	7	 11
1	12	7	 8
2	12	8	 10
3	14	13	 6
4	13	7	 6
5	18	4	 5

#define second DataFrame
df2 = pd.DataFrame({'points': [21, 25, 26],
                    'rebounds': [7, 7, 13],
                    'assists': [11, 3, 3]})

#add new row to end of DataFrame
df = df.append(df2, ignore_index = True)

#view updated DataFrame
df

        points	rebounds assists
0	10	7	 11
1	12	7	 8
2	12	8	 10
3	14	13	 6
4	13	7	 6
5	18	4	 5
6	21	7	 11
7	25	7	 3
8	26	13	 3

Note that the two DataFrames should have the same column names in order to successfully append the rows of one DataFrame to the end of another.

x