Professional Documents
Culture Documents
Dataframe - Add New Column
Dataframe - Add New Column
You can use the assign() function to add a new column to the end of a pandas DataFrame:
df = df.assign(col_name=[value1, value2, value3, …])
And you can use the insert() function to add a new column to a specific location in a pandas
DataFrame:
The following examples show how to use this syntax in practice with the following pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23],
'assists': [5, 7, 7, 9, 12, 9],
'rebounds': [11, 8, 10, 6, 6, 5]})
#view DataFrame
df
df = df.assign(steals=[2, 2, 4, 7, 4, 1])
#view DataFrame
df
Example 2: Add Multiple Columns to End of DataFrame
The following code shows how to add multiple new columns to the end of the DataFrame:
#add 'steals' and 'blocks' columns to end of DataFrame
df = df.assign(steals=[2, 2, 4, 7, 4, 1],
blocks=[0, 1, 1, 3, 2, 5])
#view DataFrame
df
#view DataFrame
df
#view DataFrame
df
Source: