Faziki
Faziki

Reputation: 821

check for column names in multiple dataframes and delete columns by name

I do see there is an answer on how to drop columns in a data frame on stackoverflow but I would like to know if it's possible to read in multiple data frames in and add a search function to go through all the data frames and search for the columns to drop

This is my current code

credits_df.drop(['keywords', 'homepage', 'status', 'tagline', 'original_language', 'homepage', 'overview', 'production_companies', 'original_title', 'title_y'], axis=1, inplace=True)

This searches in ONE Dataframe but all of these column names are in different data frames, and I think it's a bit unnecessary to add more lines of code to go through each and every data frame... Thinking there should be a 'One Ring to Rule them all' solution

Sorry if this is a silly question but I couldn't find anything on the internet related to my query

Thanks in Advance

EDIT*

Also is there a way to check for the columns and delete them IF it finds them

Upvotes: 1

Views: 669

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 4378

import pandas as pd

df1 = pd.DataFrame(columns=['keep', 'keywords', 'homepage'])
df2 = pd.DataFrame(columns=['keep', 'keywords', 'homepage'])

# organize into a list
dfs = [df1, df2]

# use list expansion to drop (could also be a loop)
[df.drop(['keywords', 'homepage'], axis=1, inplace=True) for df in dfs]

print(dfs)
# [Empty DataFrame
# Columns: [keep]
# Index: [], Empty DataFrame
# Columns: [keep]
# Index: []]
# 

Upvotes: 2

Related Questions