Table of Contents
Adding multiple columns to a Pandas DataFrame can be done by passing a list of column names and associated values to the DataFrame’s “assign” function. Each column name and associated value should be included in a separate dictionary. The “assign” function will then add the new columns to the DataFrame with the values specified. Alternatively, you can add multiple columns to the DataFrame using the DataFrame’s “eval” or “query” functions. Both of these functions take an expression which can include multiple columns and their associated values. The result of the expression will be a new DataFrame with the new columns added.
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.