Pandas DataFrame assign() Method

In this tutorial, we will learn the python pandas DataFrame.assign() method. This method assigns new columns to a DataFrame and returns a new object with all original columns in addition to new ones. The columns which are already existing and that are re-assigned will be overwritten.

The below shows the syntax of DataFrame.assign() method.

Syntax

DataFrame.assign(**kwargs)

Parameters

**kwargs: The column names represent keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change the input DataFrame. If the values are not callable such as Series, scalar, or array, they are simply assigned.

Example 1: Assigning a new column to the DataFrame using the DataFrame.assign() Method

We can add a new column to the DataFrame using the DataFrame.assign() method. The below example shows the same.

import pandas as pd
data = {'A':[1,2,3,4,5],'B':[6,7,8,9,10]}
df = pd.DataFrame(data) 
print("----After adding a column to the DataFrame----")
print(df.assign(C=[11,12,13,14,15]))

Once we run the program we will get the following result.


----After adding a column to the DataFrame----
A B C
0 1 6 11
1 2 7 12
2 3 8 13
3 4 9 14
4 5 10 15

Example 2: Assigning a new column to the DataFrame using the DataFrame.assign() Method

The below example shows how to assign a new column to the DataFrame by passing the function to the DataFrame.assign() method.

import pandas as pd
data = {'A':[1,2,3,4,5],'B':[6,7,8,9,10]}
df = pd.DataFrame(data) 
print("----After adding a column to the DataFrame----")
print(df.assign(C=lambda x: x.A+1))

Once we run the program we will get the following result.


----After adding a column to the DataFrame----
A B C
0 1 6 2
1 2 7 3
2 3 8 4
3 4 9 5
4 5 10 6

Example 3: Assigning multiple columns to the DataFrame using the DataFrame.assign() Method

We can add multiple columns to the DataFrame using the DataFrame.assign() method. The below example shows the same.

import pandas as pd
data = {'A':[1,2,3,4,5],'B':[6,7,8,9,10]}
df = pd.DataFrame(data) 
print("----After adding columns to the DataFrame----")
print(df.assign(C=lambda x: x.B+1,D=lambda x: x.C+1,E=lambda x: x.A+1))

Once we run the program we will get the following result.


----After adding columns to the DataFrame----
A B C D E
0 1 6 7 8 2
1 2 7 8 9 3
2 3 8 9 10 4
3 4 9 10 11 5
4 5 10 11 12 6

Conclusion

In this tutorial, we learned the python pandas DataFrame.assign() method. We understood the syntax and parameter, by solving examples we add the single column and multiple columns to the DataFrame.