How to add rows to Pandas 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, ...]

You can append several rows of an existing DataFrame to the end of another DataFrame using the df.append() function:

#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 a row to a Pandas DataFrame

The following code shows how to add a 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: Adding a few rows to a 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 both DataFrames should have the same column names in order to successfully append the rows of one DataFrame to the end of the other.

Guess you like

Origin blog.csdn.net/allway2/article/details/121421241