Append or Add Row to a Pandas DataFrame
0. How to append a row to a DataFrame?
1. Make a DataFrame to be Appended
Let's say you have a DataFrame of 3-year history of exam scores.
The codes below create the DataFrame.
import pandas as pd
dict_scores = {'Year' : [2019, 2020, 2021],
'Math' : [80, 70, 90],
'History' : [60, 40, 70],
'Science' : [70, 80, 60]}
df_scores = pd.DataFrame(dict_scores)
One year passed, so you need to update 1 row of the year to the DataFrame.
In 2022,
- Math score is 100.
- History score is 60.
- Science score is 90.
Use .append() method.
Make sure put column elements in lists.
dict_new = {'Year' : [2022],
'Math' : [100],
'History' : [60],
'Science' : [90]}
df_new = pd.DataFrame(dict_new)
If a ValueError like below occurs, check if the element of each column is in list or not.
dict_new = {'Year' : 2022,
'Math' : 100,
'History' : 60,
'Science' : 90}
df_new = pd.DataFrame(dict_new)
ValueError: If using all scalar values, you must pass an index
If the elements are not contained in lists,
add index argument to the pd.DataFrame() method.
df_new = pd.DataFrame(dict_new, index = [0])
2. Append the New DataFrame to the Old DataFrame.
To append the new DataFrame to old DataFrame, use .append() method.
df_scores.append(df_new)
It will make the result below.
The problem is that the index numbers do not look clean.
0 -> 1 -> 2 -> 0
The last zero(0) should be changed to 3.
Add ignore_index argument in the .append() method.
df_scores.append(df_new, ignore_index = True)
The argument ignores what the index of the new DataFrame was.
It incorporates the new DataFrame into the order of the old DataFrame.
Otherwise, you can use .reset_index() method afterwards,
instead of ignore_index argument.
df_scores.append(df_new).reset_index()