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

Time:09-19

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?

CodePudding user response:

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]

CodePudding user response:

for df in df_all:
    df.drop(df.columns[df.columns.str.contains('Unnamed:')], 1, inplace=True)
  • Related