Pandas: Add a line to the end of a dataframe

This article describes how to add a line to a pandas dataframe. The code, the result and the explanation are provided in this article.

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

With the functions concat, append, you can quickly get lost and not know how to add a line to a dataframe.

There are in fact several ways to do this. Here, I propose a simple example with the following dataframe:

abc
123
456
789

We want to add the following line:

abc
101112

With the append() function

We can add a line to a dataframe with the append() function. This function will merge two dataframes and add the lines of the second dataframe to the end of the first.

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 = df.append(df2, ignore_index=True)

# Display of the result
print(df)

The result of this code is the following:

abc
123
456
789
101112

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.

To learn more on the diffenreces between append() and concat(), you can read this article: Pandas : concat vs append

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 result is the same as with the append() function.