Can we add a new column at a specific position in a Pandas Dataframe?


#1

Question

Can we add a new column at a specific position in a Pandas dataframe?

Answer

Yes, you can add a new column in a specified position into a dataframe, by specifying an index and using the insert() function. By default, adding a column will always add it as the last column of a dataframe.

Say for example, we had a dataframe with five columns. If we wanted to insert a new column at the third position (index 2), we could do so like this:

# Third position would be at index 2, because of zero-indexing.
df.insert(2, 'new-col', data)

This will insert the column at index 2, and fill it with the data provided by data. When inserting, the columns from index 2 onward will effectively be shifted over to the right by 1 index each. The column that was previously at index 2 would now be at index 3 and so on for the following columns.