Pandas DataFrame Insert Column


The Pandas insert method allows you to insert a column in a DataFrame.

DataFrameName.insert(loc, column, value, allow_duplicates = False)

loc: loc is an integer which is the location of column where we want to insert new column. This will shift the existing column at that position to the right.

column: column is a string which is name of column to be inserted.

value: value is simply the value to be inserted. It can be int, string, float or anything or even series / List of values. Providing only one value will set the same value for all rows.

allow_duplicates: allow_duplicates is a boolean value which checks if column with same name already exists or not.

import pandas as pd  # import the pandas library into Python
data = {'firstname': ['Bob', 'Sally', 'Suzie', 'Rohan'],
       'amount': [12, 67, 33, 41]}
df = pd.DataFrame(data)
df
df.insert(1, "column", "stuff")
df

df.insert(3, "double", df['amount'] * 2)
df

For comparison purposes, the SQL syntax for adding a column in a table is ALTER TABLE table_name ADD column_name datatype;

Leave a Reply