How to add new columns?

QuestionsQuestions8 SkillsProData Selection in PandasNov, 01 2025
077

You can add new columns to a DataFrame in pandas using several methods. Here are a few common ways:

1. Using the assign() method

You can use the assign() method to add new columns:

import pandas as pd

# Sample DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35]
}

df = pd.DataFrame(data)

# Add a new column 'Sex'
df = df.assign(Sex=['F', 'M', 'M'])

print(df)

2. Directly assigning a new column

You can also add a new column by directly assigning a list or a Series to a new column name:

# Add a new column 'Salary'
df['Salary'] = [50000, 60000, 70000]

print(df)

3. Using the insert() method

If you want to add a column at a specific position, you can use the insert() method:

# Insert a new column 'Country' at index 1
df.insert(1, 'Country', ['USA', 'UK', 'Canada'])

print(df)

These methods will allow you to add new columns to your DataFrame as needed.

0 Comments

no data
Be the first to share your comment!