How to Append a List to a Pandas DataFrame (With Example)


You can use the following basic syntax to append a list to a pandas DataFrame:

#define list
new_list = ['value1', 'value2', value3, value4]

#append list to DataFrame
df.loc[len(df)] = new_list

The following example shows how to use this syntax in practice.

Example: Append List to Pandas DataFrame

Suppose we have the following pandas DataFrame that contains information about various basketball teams:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28, 22],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4, 8],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12, 9]})

#view DataFrame
df

	team	points	assists	rebounds
0	A	18	5	11
1	B	22	7	8
2	C	19	7	10
3	D	14	9	6
4	E	14	12	6
5	F	11	9	5
6	G	20	9	9
7	H	28	4	12
8	I	22	8	9

We can use the following code to append a list that contains information about a new basketball team to the end of the DataFrame:

#define list of values
new_team = ['J', 30, 10, 12]

#append list to DataFrame
df.loc[len(df)] = new_team

#view updated DataFrame
df

	team	points	assists	rebounds
0	A	18	5	11
1	B	22	7	8
2	C	19	7	10
3	D	14	9	6
4	E	14	12	6
5	F	11	9	5
6	G	20	9	9
7	H	28	4	12
8	I	22	8	9
9	J	30	10	12

Notice that the list of values has been appended as a new row to the end of the DataFrame.

Note that you’ll receive an error if the number of values in the list does not match the number of columns in the existing DataFrame.

For example, suppose we attempt to append the following list to the end of the DataFrame:

#define list of values
new_team = ['J', 30]

#append list to DataFrame
df.loc[len(df)] = new_team

#view updated DataFrame
df

ValueError: cannot set a row with mismatched columns

We receive an error because our list contains two values, but the existing pandas DataFrame contains four columns.

To append a list to the end of this DataFrame, the list must also contain four values.

Additional Resources

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

How to Convert Pandas Index to a List
How to Convert Pandas DataFrame Columns to int
How to Add Multiple Columns to Pandas DataFrame

Leave a Reply

Your email address will not be published. Required fields are marked *