Dropping mutliple columns with specific text of a dataframe within a list of dataframes python

Question:

I have a list of dataframes and each dataframe has columns that contains columns names such as "Unnamed 1", "Unnamed 2" etc

I want to drop all columns that contain the name "Unnamed" from each dataframe in the list of dataframes.

df_all = [df1,df2,df3]
df_all2 = []

for df in df_all:
    df = df[df.columns.drop(list(df.filter(regex='Unnamed')))]
    df_all2 = df.append
    df_all = df_all2 

This works, however, is there a more succinct method?

Asked By: Spooked

||

Answers:

There is a better way by using regex column filter with negative lookahead

df_all = [df.filter(regex=r'^(?!Unnamed)') for df in df_all]
Answered By: Shubham Sharma
for df in df_all:
    df.drop(df.columns[df.columns.str.contains('Unnamed:')], 1, inplace=True)
Answered By: Arvindh
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.