How to Add a New Column to an Existing Pandas Dataframe?

python

To add a new column to an existing pandas dataframe, you can simply assign a new column to the dataframe using the indexing operator [] or the assign() method.

Here are two ways to add a new column to a pandas dataframe:

# Example dataframe
import pandas as pd
data = {'name': ['John', 'Emma', 'Peter', 'Lucy'], 'age': [25, 30, 35, 40]}
df = pd.DataFrame(data)

# Method 1: Using indexing operator []
df['gender'] = ['Male', 'Female', 'Male', 'Female']
print(df)

# Method 2: Using assign() method
df = df.assign(salary=[50000, 60000, 70000, 80000])
print(df)

Output:

# Method 1
    name  age  gender
0   John   25    Male
1   Emma   30  Female
2  Peter   35    Male
3   Lucy   40  Female

# Method 2
    name  age  salary
0   John   25   50000
1   Emma   30   60000
2  Peter   35   70000
3   Lucy   40   80000

The first method adds a new column 'gender' to the dataframe by assigning a list of values to it. The second method uses the assign() method to create a new column 'salary' with a list of values. Both methods reflect the new columns in the dataframe.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?