INGl0R1AM0R1
INGl0R1AM0R1

Reputation: 1628

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

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]
})

Upvotes: 0

Views: 53

Answers (2)

User
User

Reputation: 826

You can use a comprehension:

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

Output:

carr carrer
One Two

Upvotes: 2

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

You can use DataFrame.filter

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

   Carrer  Carr
0       1     2
1       2     3
2       3     1

Upvotes: 4

Related Questions