Search code snippets, questions, articles...

Insert new column with default value in Pandas DataFrame

To add a column with some default value in rows to a pandas Dataframe, we can use the methods explained here.
import pandas as pd

data = {
  'alphabets': ['a', 'b', 'c', 'd']
}

# Create dataframe
df = pd.DataFrame(data)

print(df)

# Add new column with default value 0
df['code'] = 0

print(df)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

  alphabets
0         a
1         b
2         c
3         d

  alphabets  code
0         a     0
1         b     0
2         c     0
3         d     0

Using the above code example we are adding a new column "code" to DataFrame df with default value 0 to all the rows of column "code".

Example 2: Use assign() function to add column with default value

We can also use the assign() function of Pandas DataFrame to add a column with a default value to an existing DataFrame. To insert column "code" with default value 0 to a Dataframe df using Dataframe.assign() function, we can use the below code

Code Example

import pandas as pd

data = {
  'alphabets': ['a', 'b', 'c', 'd']
}

# Create dataframe
df = pd.DataFrame(data)

# Add new column with default value 0 - using assing() function
df = df.assign(code=0)

print(df)

Output

  alphabets  code
0         a     0
1         b     0
2         c     0
3         d     0
import pandas as pd

data = {
  'alphabets': ['a', 'b', 'c', 'd']
}

# Create dataframe
df = pd.DataFrame(data)

# Add new column with default value None
df['new_column'] = None

print(df)

#   alphabets new_column
# 0         a       None
# 1         b       None
# 2         c       None
# 3         d       None
Here we are adding default value None while inserting a new column to an existing DataFrame df.
import pandas as pd

data = {
  'alphabets': ['a', 'b', 'c', 'd'],
  'numeric_vals': [10, 20, 30, 40]
}

# Create dataframe
df = pd.DataFrame(data)

df.insert(1, 'new_column', 0, True)

print(df)

#   alphabets  new_column  numeric_vals
# 0         a           0            10
# 1         b           0            20
# 2         c           0            30
# 3         d           0            40
The insert() function of pandas DataFrame can also be used to add a column with default values to a DataFrame. We are adding a value 0 to all the rows of column new_column at location 1.
Was this helpful?
0 Comments