Hit enter after type your search item

3 Examples to Add Column in a Pandas Data Frame

How to add a column in an existing data frame using Pandas?

In this tutorial, we will show you different ways of adding columns in the Pandas data frame.

For the examples, we have the following data frame created:

Code:


Output:

Using the insert method of the data frame

The insert is a data frame method that is used to add a column in the specified position.

A duplicate column name can also be added if allow_duplicate is set to True.

See the example below where we will add a new column (“Difference”) in the above-created data frame.

Code:


Output:

How did it work?
  • We want to add a new column with the name “Difference” in the DF.
  • In the insert method, we specified position 1 (0-based index) for the “Difference” column.
  • By using insert, you may also provide data. We provided data in the list.

Second Way – want to add a column at the end of the existing Data Frame?

This is the easiest way of adding a new column along with data in the existing data frame. However, the drawback is, it can add a column at the end.

For that, simply use the DF name along with the new column and assign the values in a list – that’s it.

Have a look at the example below where we will add the “Difference” column in the above-created DF.

Code:


Result:

pandas-df-add-column

You can see the newly added column is placed at the end of DF.

Third way – Using a dictionary/map for adding a column

You may also use a Python dictionary and map combination for adding a new column in the existing data frame.

Code:


Output:

How did it work?
  • In that case, we passed the dictionary to the map
  • It will perform a lookup and return the associated value for that key.
  • Alternatively, we used a column from the existing DF and passed a new column’s value to it.

Conclusion:

Due to its flexibility (for allowing adding columns at any position), we may categorize Data Frame’s insert method as the better way for adding columns in the data frame.

This div height required for enabling the sticky sidebar