How To Add A New Column To An Existing DataFrame?

To add a new column to an existing DataFrame in Python, you can use either of the following methods:

  1. Using bracket notation:
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Add a new column 'C' and assign values to it
df['C'] = [7, 8, 9]

print(df)

Output:

   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9
  1. Using assign method:
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Use the assign method to add a new column 'C' and assign values to it
df = df.assign(C=[7, 8, 9])

print(df)

Output:

   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9

Both approaches will add a new column named ‘C’ to the DataFrame df and assign values to it.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!