How To Add a Column to a Pandas DataFrame

There are two ways to add a column to a Pandas DataFrame:

Using the assign() method

import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Carol'], 'age': [25, 30, 35]})
df = df.assign(occupation=['Software Engineer', 'Data Scientist', 'Product Manager'])

print(df)

Using the insert() method:

import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Carol'], 'age': [25, 30, 35]})
df.insert(2, 'occupation', ['Software Engineer', 'Data Scientist', 'Product Manager'])

print(df)

The assign() method is more efficient than the insert() method, especially when adding a new column to a large DataFrame.

Leave a Reply