Keep only certain columns in a dataframe

This technical problem deals with how to keep only certain columns in a dataframe using Python. A function is provided that takes in a dataframe and a list of column names, and returns a new dataframe with only the columns in the list. An example is given of input and output.

Problem

Write a function that takes in a dataframe and a list of column names and returns a new dataframe with only the columns in the list.
Example input:
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]})
columns_to_keep = ['col1', 'col3']
Example output:
df = pd.DataFrame({'col1': [1, 3], 'col3': [7, 9]})

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
import pandas as pd

def keep_columns(df, columns_to_keep):
    return df[columns_to_keep]

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]})
columns_to_keep = ['col1', 'col3']

print(keep_columns(df, columns_to_keep))

A.I. Evaluation of the Solution

This solution is complete and solves the problem. The approach is straightforward and easy to follow.

Evaluated at: 2022-11-12 06:16:24