How to Add or Insert Row to Pandas DataFrame
To add/insert a new row into a Pandas DataFrame use the DataFrame.append()
function.
Let's begin by looking at the syntax of the Pandas .append()
function before we look at some examples.
Pandas .append() Syntax
Here is the syntax of the Pandas .append()
function:
DataFrame.append(new_row, ignore_index=False, verify_integrity=False, sort=False)
DataFrame
– The DataFrame data to append to (.append()
does not modify the original DataFrame.)new_row
– The data to append.ignore_index
– IfTrue
, the resulting axis will be labelled 0, 1.verify_integrity
– If True, duplicate index entries will throw a ValueError.sort
– Sort columns.
Typically, the only two arguments you will need to use for appending data are new_row
and ignore_index
.
Add Row to DataFrame
It is important to remember that .append()
will not add data to the existing DataFrame, instead, it will create a new one with the appended row. You can choose whether to store the result in a new variable or overwrite the existing one.
import pandas as pd
data = {
'name': ['John', 'Amy', 'Alice'],
'age': [29, 25, 23],
'weight': [160, 130, 140],
'height': [172, 150, 160]
}
df = pd.DataFrame(data)
print('Original DataFrame:\n----------')
print(df)
new_row = {'name':'James', 'age':37, 'weight':192, 'height':187}
df = df.append(new_row, ignore_index=True)
print('\n\nNew DataFrame with row added:\n---------')
print(df)
Original DataFrame:
----------
name age weight height
0 John 29 160 172
1 Amy 25 130 150
2 Alice 23 140 160
New DataFrame with row added:
---------
name age weight height
0 John 29 160 172
1 Amy 25 130 150
2 Alice 23 140 160
3 James 37 192 187
Note – Dictionaries can only be appended if ignore_index=True
or you will get a TypeError
.
Append Dictionary to DataFrame When ignore_index is False
To append a dictionary to a Pandas DataFrame with ignore_index
set to False
, use pd.Series()
like this:
import pandas as pd
data = {
'name': ['John', 'Amy', 'Alice'],
'age': [29, 25, 23],
'weight': [160, 130, 140],
'height': [172, 150, 160]
}
df = pd.DataFrame(data)
print('Original DataFrame:\n----------')
print(df)
new_row = pd.Series(data={'name':'James', 'age':37, 'weight':192, 'height':187}, name='n')
df = df.append(new_row, ignore_index=False)
print('\n\nNew DataFrame with row added:\n---------')
print(df)
Original DataFrame:
----------
name age weight height
0 John 29 160 172
1 Amy 25 130 150
2 Alice 23 140 160
New DataFrame with row added:
---------
name age weight height
0 John 29 160 172
1 Amy 25 130 150
2 Alice 23 140 160
n James 37 192 187