Extracting specific selected columns to new DataFrame as a copy

To create a new DataFrame with a subset of columns from an existing DataFrame, you can use the pandas library.

Here's an example of how to do this:

import pandas as pd

# Load the data into a DataFrame
df = pd.read_csv("data.csv")

# Select the columns you want to keep
selected_columns = ['col1', 'col3']

# Create a new DataFrame with only the selected columns
new_df = df[selected_columns].copy()

print(new_df)

Watch a course Python - The Practical Guide

This will create a new DataFrame that contains only the col1 and col3 columns from the original DataFrame.

Note that the copy method is used to create a new DataFrame with its own copy of the data. Without the copy method, the new DataFrame will be a view of the original DataFrame, and any changes made to the new DataFrame will be reflected in the original.