You can use the following methods to add a column with a constant value to a pandas DataFrame:
Method 1: Add One Column with Constant Value
df['new'] = 5
Method 2: Add Multiple Columns with Same Constant Value
df[['new1', 'new2', 'new3']] = 5
Method 3: Add Multiple Columns with Different Constant Values
#define dictionary of new values new_constants = {'new1': 5, 'new2': 10, 'new3': 15} #add multiple columns with different constant values df = df.assign(**new_constants)
The following examples show how to use each method with the following pandas DataFrames:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'points': [18, 22, 19, 14, 14, 11, 20, 28],
'assists': [5, 7, 7, 9, 12, 9, 9, 4]})
#view DataFrame
print(df)
team points assists
0 A 18 5
1 B 22 7
2 C 19 7
3 D 14 9
4 E 14 12
5 F 11 9
6 G 20 9
7 H 28 4
Example 1: Add One Column with Constant Value
The following code shows how to add one column with a value of 5 for each row:
#add column with constant value
df['new'] = 5
#view updated DataFrame
print(df)
team points assists new
0 A 18 5 5
1 B 22 7 5
2 C 19 7 5
3 D 14 9 5
4 E 14 12 5
5 F 11 9 5
6 G 20 9 5
7 H 28 4 5
The new column called new is filled with the constant value of 5 for each row.
Example 2: Add Multiple Columns with Same Constant Value
The following code shows how to add multiple columns that all have the same constant value of 5:
#add three new columns each with a constant value of 5
df[['new1', 'new2', 'new3']] = 5
#view updated DataFrame
print(df)
team points assists new1 new2 new3
0 A 18 5 5 5 5
1 B 22 7 5 5 5
2 C 19 7 5 5 5
3 D 14 9 5 5 5
4 E 14 12 5 5 5
5 F 11 9 5 5 5
6 G 20 9 5 5 5
7 H 28 4 5 5 5
Notice that each new column contains the value 5 in each row.
Example 3: Add Multiple Columns with Different Constant Values
The following code shows how to add multiple columns with different constant values:
#define dictionary of new values
new_constants = {'new1': 5, 'new2': 10, 'new3': 15}
#add multiple columns with different constant values
df = df.assign(**new_constants)
#view updated DataFrame
print(df)
team points assists new1 new2 new3
0 A 18 5 5 10 15
1 B 22 7 5 10 15
2 C 19 7 5 10 15
3 D 14 9 5 10 15
4 E 14 12 5 10 15
5 F 11 9 5 10 15
6 G 20 9 5 10 15
7 H 28 4 5 10 15
Notice that each of the three new columns have a different constant value.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
How to Rename Columns in Pandas
How to Add a Column to a Pandas DataFrame
How to Add Empty Column to Pandas DataFrame
How to Change Order of Columns in Pandas DataFrame