Hit enter after type your search item

Pandas Data Frame Insert Method

Pandas Data Frame Insert method

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

If a newly added column name already exists then an error occurs.

In order to add a duplicate column, you may use the allow_duplicate= True

Syntax of insert method

DataFrame.insert(loc, column, value, allow_duplicates=_NoDefault.no_default)

An example of the insert to add a new column

For our examples, we have the following data frame created by using this Python program:


Data Frame:

In the example below, we will only use three arguments in the insert method.

The first argument specifies the position – where to add the column.

It’s a 0-based index, so we provided 2 to add the column after the ID column.

Then we provided the column name and the last argument contains the values for the new column.

Python program:



You can see, the Difference column is added after the first column “Year”.

The example of adding a duplicate column

As mentioned earlier, Python will generate an error if you try adding a column name that already exists. See below where we used the insert method for adding a column “Name” in the above-created data frame.



So, it generated the ValueError.

Using allow_duplicates in the insert method

In order to allow adding a duplicate column, you may use the allow_duplicates argument as follows:

allow_duplicates = True

See the same example as above and the output.




This div height required for enabling the sticky sidebar