Extracting Specific Selected Columns To New DataFrame As A Copy

To extract specific selected columns from a DataFrame and create a new DataFrame as a copy, you can use the loc or iloc method.

Here’s an example:

import pandas as pd

# Creating a sample DataFrame
data = {'Name': ['John', 'Emma', 'Liam', 'Olivia'],
        'Age': [25, 28, 30, 32],
        'City': ['New York', 'London', 'Sydney', 'Paris']}
df = pd.DataFrame(data)

# Creating a new DataFrame with selected columns
new_df = df.loc[:, ['Name', 'City']]
# or
new_df = df.iloc[:, [0, 2]]

print(new_df)

Output:

    Name      City
0   John  New York
1   Emma    London
2   Liam    Sydney
3  Olivia     Paris

In the above example, the loc method is used to extract columns with labels ‘Name’ and ‘City’ from the original DataFrame and create a new DataFrame new_df. You can also use the iloc method to achieve the same result by specifying column indices [0, 2] instead of labels.

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!