0

I have a list:

['Ad','Cs']

And a df

       xx  yy  zz
Adjsl   5   7   9
Adjrr   1   1   2
Blsda   6   6   6
Csaosq  8   7   2

I would like to know how could I slice the df by only keeping the rows those index beggin with the elements of the list to obtain the following output:

       xx  yy  zz
Adjsl   5   7   9
Adjrr   1   1   2
Csaosq  8   7   2
JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

2 Answers2

1

You can use match:

lst = ['Ad','Cs']
pattern = '|'.join(lst)

df[df.index.str.match(f'^({pattern})')]

output:

        xx  yy  zz
Adjsl    5   7   9
Adjrr    1   1   2
Csaosq   8   7   2
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
1

we use Series.str.startswith. Here you can combine it with pd.concat:

df_filtered=pd.concat([df[df.index.str.startswith(key)] for key in my_list])
print(df_filtered)

        xx  yy  zz
Adjsl    5   7   9
Adjrr    1   1   2
Csaosq   8   7   2
ansev
  • 30,322
  • 5
  • 17
  • 31