Using insert() method

If you need to insert column into DataFrame at specified location then pandas.DataFrame.insert() should do the trick. However, you should make sure that the column is first taken out of the original DataFrame otherwise a ValueError will be raised with the following message:

ValueError: cannot insert column_name, already exists

Therefore, before calling insert() we first need to do a pop() over the DataFrame in order to drop the column from the original DataFrame and retain its information. For instance, if we want to place colD as the first column of the frame we first need to pop() the column and then insert it back, this time to the desired index.

col = df.pop("colD")
df.insert(0,, col)

# colD colA colB colC
# 0 10 1 a True
# 1 20 2 b False
# 2 30 3 c False

Continue reading:—-7f60cf5620c9—4