How to append a new row to a Pandas DataFrame?
Published on Aug. 22, 2023, 12:18 p.m.
To append a new row to a Pandas DataFrame, you can use the append()
method. Here’s an example:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # create a DataFrame with columns A and B
new_row = {'A': 4, 'B': 7} # create a dictionary representing the new row to be added
df = df.append(new_row, ignore_index=True) # append the new row to the DataFrame
print(df)
Output:
A B
0 1 4
1 2 5
2 3 6
3 4 7
In the example above, new_row
stores a dictionary representing the new row we want to add to the DataFrame. The append()
method adds the new row to the DataFrame, ignoring the original index and using a new index instead. The modified DataFrame is then stored back into the original DataFrame.
Note that if you want to preserve the index of the original DataFrame, you can set the ignore_index
argument to False:
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # create a DataFrame with columns A and B
new_row = {'A': 4, 'B': 7} # create a dictionary representing the new row to be added
df = df.append(new_row, ignore_index=False) # append the new row to the DataFrame, preserving the original index
print(df)
Output:
A B
0 1 4
1 2 5
2 3 6
3 4 7
In summary, to append a new row to a Pandas DataFrame, create a dictionary representing the new row, then use the append()
method to add the row to the DataFrame, either preserving or ignoring the original index as desired.