Pandas DataFrame insert() Method
Pandas DataFrame insert() Method
In this tutorial, we will learn the Python pandas DataFrame.insert() method. This method inserts the column into DataFrame at the specified location. It raises a ValueError if the column is already contained in the DataFrame unless allow_duplicates is set to True.
The below shows the syntax of the DataFrame.insert() method.
Syntax
DataFrame.insert(loc, column, value, allow_duplicates=False)Parameters
loc: int. Insertion index. Must verify 0 <= loc <= len(columns).
column: str, number, or hashable object. Label of the inserted column.
value: int, Series, or array-like
allow_duplicates: bool, optional
Example 1: Inserting new column into the DataFrame
We can insert a new column to the DataFrame using the DataFrame.insert() method. See, how it works in the below example.
#importing pandas as pd
import pandas as pd
df=pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8]})
print("The DataFrame is")
print(df)
print("Adding column to the DataFrame")
df.insert(2,'C',1)
print(df)Once we run the program we will get the following output.
Output:
The DataFrame is
A B
0 1 5
1 2 6
2 3 7
3 4 8
Adding column to the DataFrame
A B C
0 1 5 1
1 2 6 1
2 3 7 1
3 4 8 1
Example 2: Inserting new column into the DataFrame
We can insert a Series as column of the DataFrame using the DataFrame.insert() method. It will return a new dataframe after adding the column.
#importing pandas as pd
import pandas as pd
df=pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8]})
print("The DataFrame is")
print(df)
print("Adding column to the DataFrame")
df.insert(0,'C',1)
print(df)Once we run the program we will get the following output.
Output:
The DataFrame is
A B
0 1 5
1 2 6
2 3 7
3 4 8
Adding column to the DataFrame
C A B
0 1 1 5
1 1 2 6
2 1 3 7
3 1 4 8
Example : Error while inserting the column to the DataFrame
The DataFrame.insert() method raises a ValueError, if the column is already contained in the DataFrame.
#importing pandas as pd
import pandas as pd
df=pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8]})
print("Adding column to the DataFrame")
df.insert(2,'A',1)
print(df)Once we run the program we will get the following output.
Output:
ValueError: cannot insert A, already exists
Conclusion
In this tutorial, we learned the Python pandas DataFrame.insert() method. We learned the syntax and applying this method in the examples.










