Home > Net >  Interact through df columns and filter then with a like string statement
Interact through df columns and filter then with a like string statement

Time:06-13

Imagine a dataset with multiple columns, that start with carr

carr carrer banana
One Two Three

How can i filter through these columns names, and return only those who start with the string "carr".

Wanted result

carr carrer
One Two

Sample df:

import pandas as pd
pd.DataFrame({
    "Carrer":[1,2,3],
    "Carr":[2,3,1],
    "Banana":[1,5,7]
})

CodePudding user response:

You can use DataFrame.filter

out = df.filter(regex='(?i)^carr')
print(out)

   Carrer  Carr
0       1     2
1       2     3
2       3     1

CodePudding user response:

You can use a comprehension:

sub = [col for col in df.columns if col.lower().startswith('carr')]
df[sub]

Output:

carr carrer
One Two
  • Related