With Pandas, you can add a line to a dataframe, however, there are no method to simply just add a line to the end of a dataframe. You have to create a new dataframe with the new line and then concatenate the two dataframes. If you wanted to add data line by line, it should be better to use a list of dictionaries, numpy arrays or list, and then convert it to a dataframe.
Add a line to the beginning or end of a dataframe
The supported approach is to create a one-row DataFrame and combine it with concat().
There are in fact several ways to do this. Here, I propose a simple example with the following dataframe:
| a | b | c |
|---|---|---|
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
We want to add the following line:
| a | b | c |
|---|---|---|
| 10 | 11 | 12 |
With the concat() function
We can also add a line to a dataframe with the concat() function. This function will merge two dataframes and add the lines of the second dataframe to the end of the first.
DataFrame.append() was removed in pandas 2.0, so older examples using it should be replaced with concat().
We will therefore create a dataframe with the line to add and merge it with the initial dataframe:
import pandas as pd
# Creation of the initial dataframe
df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]], columns=['a','b','c'])
# Creation of the dataframe containing the line to add
df2 = pd.DataFrame([[10,11,12]], columns=['a','b','c'])
# Merge of the two dataframes
df = pd.concat([df, df2], ignore_index=True)
# Display of the result
print(df)
The resulting DataFrame contains the new row at index 3.