You can use the following basic syntax to add a row to an empty pandas DataFrame:
#define row to add some_row = pd.DataFrame([{'column1':'value1', 'column2':'value2'}]) #add row to empty DataFrame df = pd.concat([df, some_row])
The following examples show how to use this syntax in practice.
Example 1: Add One Row to Empty DataFrame
The following code shows how to add one row to an empty pandas DataFrame:
import pandas as pd #create empty DataFrame df = pd.DataFrame() #define row to add row_to_append = pd.DataFrame([{'team':'Mavericks', 'points':'31'}]) #add row to empty DataFrame df = pd.concat([df, row_to_append]) #view updated DataFrame print(df) team points 0 Mavericks 31
Notice that we created an empty DataFrame by using pd.DataFrame(), then added one row to the DataFrame by using the concat() function.
Example 2: Add Multiple Rows to Empty DataFrame
The following code shows how to add multiple rows to an empty pandas DataFrame:
import pandas as pd #create empty DataFrame df = pd.DataFrame() #define rows to add rows_to_append = pd.DataFrame([{'team':'Mavericks', 'points':'31'}, {'team':'Hawks', 'points':'20'}, {'team':'Hornets', 'points':'25'}, {'team':'Jazz', 'points':'43'}]) #add row to empty DataFrame df = pd.concat([df, rows_to_append]) #view updated DataFrame print(df) team points 0 Mavericks 31 1 Hawks 20 2 Hornets 25 3 Jazz 43
Once again we created an empty DataFrame by using pd.DataFrame(), then added multiple rows to the DataFrame by using the concat() function.
Note: You can find the complete documentation for the pandas concat() function here.Â
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
How to Rename Columns in Pandas
How to Add a Column to a Pandas DataFrame
How to Change the Order of Columns in Pandas DataFrame