Add new column to Pandas dataframe with default value
Pandas
import modules
import pandas as pd
import numpy as np
create dummy dataframe
raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
'age': [20, 19, 22, 21],
'favorite_color': ['blue', 'red', 'yellow', "green"],
'grade': [88, 92, 95, 70]}
df = pd.DataFrame(raw_data, index = ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'])
df
age | favorite_color | grade | name | |
---|---|---|---|---|
Willard Morris | 20 | blue | 88 | Willard Morris |
Al Jennings | 19 | red | 92 | Al Jennings |
Omar Mullins | 22 | yellow | 95 | Omar Mullins |
Spencer McDaniel | 21 | green | 70 | Spencer McDaniel |
add new column to pandas dataframe with default value
#here is the simplist way to add the new column
df['My new column'] = 'default value'
df
age | favorite_color | grade | name | My new column | |
---|---|---|---|---|---|
Willard Morris | 20 | blue | 88 | Willard Morris | default value |
Al Jennings | 19 | red | 92 | Al Jennings | default value |
Omar Mullins | 22 | yellow | 95 | Omar Mullins | default value |
Spencer McDaniel | 21 | green | 70 | Spencer McDaniel | default value |
#if you want to specify the order of the column, you can use insert
#here, we are inserting at index 1 (so should be second col in dataframe)
df.insert(1, 'My 2nd new column', 'default value 2')
df
age | My 2nd new column | favorite_color | grade | name | My new column | |
---|---|---|---|---|---|---|
Willard Morris | 20 | default value 2 | blue | 88 | Willard Morris | default value |
Al Jennings | 19 | default value 2 | red | 92 | Al Jennings | default value |
Omar Mullins | 22 | default value 2 | yellow | 95 | Omar Mullins | default value |
Spencer McDaniel | 21 | default value 2 | green | 70 | Spencer McDaniel | default value |