• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar

Python and R Tips

Learn Data Science with Python and R

  • Home
  • Python
  • Pandas
    • Pandas 101
  • tidyverse
    • tidyverse 101
  • R
  • Linux
  • Conferences
  • Python Books
  • About
    • Privacy Policy
You are here: Home / Pandas 101 / How To Insert a Column at Specific Location in Pandas DataFrame?

How To Insert a Column at Specific Location in Pandas DataFrame?

April 1, 2020 by cmdlinetips

In this post, we will learn how to insert a column at specific location in a Pandas dataframe. We will use Pandas insert() function to insert column into DataFrame at a specified location with a specific name.

import numpy as np
import pandas as pd
pd.__version__
1.0.0

Let us create a data frame using NumPy’s random module.

# set random seed to reproduce the same data
np.random.seed(42)
# create Pandas data frame with 3 columns using numpy array
df =pd.DataFrame(np.random.randint(20, size=(8,3)),
                   columns=list('ABD'))

Our data frame looks like this. We have three columns with names A, B and D.

df.head()


        A	B	D
0	6	19	14
1	10	7	6
2	18	10	10
3	3	7	2
4	1	11	5

Let us try to insert a new column C, before the column D in the Pandas dataframe. We can use Pandas’ insert() function to insert a column. We need to specify the index of location, name of the column, and the actual column vector as arguments to insert() function.

df.insert(2,"C",np.random.randint(20, size=8))

df.head()
        A	B	C	D
0	6	19	18	14
1	10	7	11	6
2	18	10	19	10
3	3	7	2	2
4	1	11	4	5

If we try to insert a column with a name that exists in the dataframe already, like shown below.

df.insert(2,"B",np.random.randint(20, size=8))

We will get a valueError as shown below by default.

ValueError: cannot insert B, already exists

We can change the above behaviour with allow_duplicates=True while we insert a column. For example we can insert B column with allow_duplicates=True

df.insert(2,"B",np.random.randint(20, size=8),allow_duplicates=True)
df.head()

And we get a Pandas dataframe with duplicate column names.


	A	B	B	D
0	6	19	6	14
1	10	7	17	6
2	18	10	3	10
3	3	7	13	2
4	1	11	17	5

Inserting a column into a dataframe is a tricky task. A better way to add to add a column is to use two dataframe with common ID and merge them. One of the common applications of Pandas insert() function is to move a column to the front of the dataframe.

This post is part of the series on Pandas 101, a tutorial covering tips and tricks on using Pandas for data munging and analysis.

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related posts:

Default ThumbnailHow To Move a Column to First Position in Pandas DataFrame? How to Change Order of Columns in PandasHow to Change the Order of Columns in a Pandas Dataframe Default ThumbnailHow To Add Identifier Column When Concatenating Pandas data frames? Default ThumbnailHow To Drop Multiple Columns in Pandas Dataframe?

Filed Under: Pandas 101, Python Tips Tagged With: Insert a column in Pandas, pandas insert()

Primary Sidebar

Subscribe to Python and R Tips and Learn Data Science

Learn Pandas in Python and Tidyverse in R

Tags

Altair Basic NumPy Book Review Data Science Data Science Books Data Science Resources Data Science Roundup Data Visualization Dimensionality Reduction Dropbox Dropbox Free Space Dropbox Tips Emacs Emacs Tips ggplot2 Linux Commands Linux Tips Mac Os X Tips Maximum Likelihood Estimation in R MLE in R NumPy Pandas Pandas 101 Pandas Dataframe Pandas Data Frame pandas groupby() Pandas select columns Pandas select_dtypes Python Python 3 Python Boxplot Python Tips R rstats R Tips Seaborn Seaborn Boxplot Seaborn Catplot Shell Scripting Sparse Matrix in Python tidy evaluation tidyverse tidyverse 101 Vim Vim Tips

RSS RSS

  • How to convert row names to a column in Pandas
  • How to resize an image with PyTorch
  • Fashion-MNIST data from PyTorch
  • Pandas case_when() with multiple examples
  • An Introduction to Statistical Learning: with Applications in Python Is Here
  • 10 Tips to customize ggplot2 title text
  • 8 Plot types with Matplotlib in Python
  • PCA on S&P 500 Stock Return Data
  • Linear Regression with Matrix Decomposition Methods
  • Numpy’s random choice() function

Copyright © 2025 · Lifestyle Pro on Genesis Framework · WordPress · Log in

Go to mobile version