Table of Contents
Adding a row to an empty dataframe in pandas can be done by first creating a dataframe with the desired columns and then using the append() method to add a row to the dataframe. The append() method takes a Series or a dictionary as argument and adds it to the existing dataframe as a row. The dataframe and the data to be added must have the same number of columns as the dataframe. The columns of the dataframe can be customised by passing the desired column names as a list to the columns parameter of the dataframe constructor.
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 .