macxpat
macxpat

Reputation: 187

Python dataframes : select columns by name and by filter

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?

Upvotes: 2

Views: 899

Answers (2)

baileythegreen
baileythegreen

Reputation: 1194

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"

Upvotes: 1

Matt Hall
Matt Hall

Reputation: 8122

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.

Upvotes: 1

Related Questions