Open In App

Add column with constant value to pandas dataframe

Prerequisite: Pandas 

In this article, we will learn how to add a new column with constant value to a Pandas DataFrame. Before that one must be familiar with the following concepts:



Approach

  1. Import Library
  2. Load or create a dataframe
  3. Add column with constant value to dataframe

To understand these above mentioned steps, lets discuss some examples :

Example 1: (By using Pandas Series)






# import packages
import pandas as pd
import numpy as np
  
# create dataframe
df = pd.DataFrame({'Number': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
                   'Power 2': {0: 1, 1: 4, 2: 9, 3: 16, 4: 25},
                   'Power 3': {0: 1, 1: 8, 2: 27, 3: 64, 4: 125}})
  
# view dataframe
print("Initial dataframe")
display(df)
  
  
# adding column with constant value
df['Power 0'] = pd.Series([1 for x in range(len(df.index))])
  
# view dataframe
print("Final dataframe")
display(df)

Output :

Example 2: (As static value)




# import packages
import pandas as pd
import numpy as np
  
# create dataframe
df = pd.DataFrame({'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Akash'},
                   'Marks': {0: 68, 1: 87, 2: 45, 3: 78, 4: 56}})
  
  
# view dataframe
print("Initial dataframe")
display(df)
  
  
# adding column with constant value
df['Pass'] = True
  
# view dataframe
print("Final dataframe")
display(df)

Output :


Article Tags :