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)
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".
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
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
0 Comments