How to add column in DataFrame by using pandas?

Pandas DataFrame.assign()

The assign() method is also responsible for adding a new column into a DataFrame.

If we re-assign an existing column, then its value will be overwritten.

Signature

DataFrame.assign(**kwargs)

Parameters

  • kwargs: keywords are the column names. These keywords are assigned to the new column if the values are callable. If the values are not callable, they are simply assigned.

Returns

It returns a new DataFrame with the addition of the new columns.

Example 1:

import pandas as pd  
# Create an empty dataframe  
info = pd.DataFrame()  
  
# Create a column  
info['ID'] = [101, 102, 103]  
  
# View the dataframe  
info  
# Assign a new column to dataframe called 'age'   
info.assign(Name = ['Smith', 'Parker', 'John'])  

Output

     ID     Name
0    101    Smith
1    102	Parker
2    103	John

Example 2:

import pandas as pd  
# Create a dataframe  
info = pd.DataFrame({'temp_c': [17.0, 25.0]},  
# Create an index that consist some values  
index=['Canada', 'Australia'])  
# View the dataframe  
info  
info.assign(temp_f=lambda x: x.temp_c * 7 / 2 + 24)  
info.assign(temp_f=lambda x: x['temp_c'] * 6 / 2 + 21,  
temp_k=lambda x: (x['temp_f'] +  342.27) * 6 / 4)  

Output

            temp_c     temp_f     temp_k
Canada       17.0       72.0     621.405
Australia    25.0       96.0     657.405