Home > Software design >  Python dataframes : select columns by name and by filter
Python dataframes : select columns by name and by filter

Time:03-30

I want to select some columns by name, like

selection = df[['Name', 'Qualification']]

and some columns by a filter like

selection = df.filter(regex=("Level.*"))

How to combine those selections in one instruction?

CodePudding user response:

If you can list all of the column names you want (as in, the number isn't massive), you can do this:

selection = df.filter(regex=("Level.*|Name|Qualification"))

The | character in the regex means or, so that line will take any column that matches one of:

  • "Level.*"
  • "Name"
  • "Qualification"

CodePudding user response:

Probably lots of ways to go but I would select them separately then use

pd.concat([selection1, selection2], axis=1)

Maybe some other ideas in the merging docs.

  • Related