Remove rows by index that startswith string in Pandas

Viewed 979

is it possible to filter rows by its index name? i need to output the rows with an index name start with "aa" and "wa".

    col1   col2
b     3       3
d     4       4
fd    5       4
s     2       5
aaa   1       6
waa   4       2

OUTPUT:

     col1   col2
aaa    1       6
waa    4       2
3 Answers

Try with startwith and pass a touple inside it.


import pandas as pd
df = pd.DataFrame({'col1': [3,4,5,2,1,4, 6], 'col2': [3,4,4,5,6,2, 6]}, index=['b', 'd', 'fd', 's', 'aa', 'wa', 'aaa'])

df[df.index.str.startswith(('aa', 'wa'))]

Output:

    col1  col2
aa   1       6
wa   4       2
aaa  6       6

You could do something like this

df = pd.DataFrame({'id': ['b', 'd', 'fd', 's', 'aa', 'wa', 'aaa'], 'col1': [1,2,3,4,5,6, 7]})
df.set_index('id', inplace=True)
df.loc[(df.index.str.startswith('aa')) | (df.index.str.startswith('wa')), :]

This should also work with multiple columns

thanks for answering. i also found a solution.

df.index.name = "type" # setting an index name

          col1   col2
   type 
    b      3       3
    d      4       4
    fd     5       4
    s      2       5
    aaa    1       6
    waa    4       2

df.reset_index(inplace=True) # converts index type into column to manipulate

        type   col1   col2
    1    b      3       3
    2    d      4       4
    3    fd     5       4
    4    s      2       5
    5    aaa    1       6
    6    waa    4       2

df_aa = df[df["type"].str.startswith('aa')] #filtering type that starts with "aa"

        type   col1   col2
    1    aaa    1       6

df_wa = df[df["type"].str.startswith('wa')] #filtering type that starts with "wa"

         type  col1   col2
    1    waa    4       2

df = pd.concat([df_aa , df_wa], axis=0) #combining dataframe vertically by using axis 0

         type  col1   col2
    1    aaa    1       6
    2    waa    4       2
Related