You can use the following methods to add multiple columns to a pandas DataFrame:
Method 1: Add Multiple Columns that Each Contain One Value
df[['new1', 'new2', 'new3']] = pd.DataFrame([[4, 'hey', np.nan]], index=df.index)
Method 2: Add Multiple Columns that Each Contain Multiple Values
df['new1'] = [1, 5, 5, 4, 3, 6] df['new2'] = ['hi', 'hey', 'hey', 'hey', 'hello', 'yo'] df['new3'] = [12, 4, 4, 3, 6, 7]
The following examples show how to use each method with the following pandas DataFrame:
import pandas as pd import numpy as np #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F'], 'points': [18, 22, 19, 14, 14, 11], 'assists': [5, 7, 7, 9, 12, 9]}) #view DataFrame 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
Method 1: Add Multiple Columns that Each Contain One Value
The following code shows how to add three new columns to the pandas DataFrame in which each new column only contains one value:
#add three new columns to DataFrame
df[['new1', 'new2', 'new3']] = pd.DataFrame([[4, 'hey', np.nan]], index=df.index)
#view updated DataFrame
df
team points assists new1 new2 new3
0 A 18 5 4 hey NaN
1 B 22 7 4 hey NaN
2 C 19 7 4 hey NaN
3 D 14 9 4 hey NaN
4 E 14 12 4 hey NaN
5 F 11 9 4 hey NaN
Notice that three new columns – new1, new2, and new3 – have been added to the DataFrame.
Also notice that each new column contains only one specific value.
Method 2: Add Multiple Columns that Each Contain Multiple Values
The following code shows how to add three new columns to the pandas DataFrame in which each new column contains multiple values:
#add three new columns to DataFrame
df['new1'] = [1, 5, 5, 4, 3, 6]
df['new2'] = ['hi', 'hey', 'hey', 'hey', 'hello', 'yo']
df['new3'] = [12, 4, 4, 3, 6, 7]
#view updated DataFrame
df
team points assists new1 new2 new3
0 A 18 5 1 hi 12
1 B 22 7 5 hey 4
2 C 19 7 5 hey 4
3 D 14 9 4 hey 3
4 E 14 12 3 hello 6
5 F 11 9 6 yo 7
Notice that three new columns – new1, new2, and new3 – have been added to the DataFrame.
Also notice that each new column contains multiple values.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Sort by Multiple Columns in Pandas
How to Check if Column Exists in Pandas
How to Rename Columns in Pandas