I have string index in pandas DataFrame how can I select by startswith?

38,729

Use index which works with str nice:

df[df.index.str.startswith('U')]

Sample:

df = pd.DataFrame({'Nation':['Uw','A', 'Ur'],
                   'A':[2,3,5],
                   'Z':[4,5,6]})


df = df.set_index(['Nation'])
print (df)
        A  Z
Nation      
Uw      2  4
A       3  5
Ur      5  6

print (df[df.index.str.startswith('U')])
        A  Z
Nation      
Uw      2  4
Ur      5  6

If need select by level of MultiIndex use get_level_values:

df = df.set_index(['Nation', 'A'])
print (df)
          Z
Nation A   
Uw     2  4
A      3  5
Ur     5  6

print (df[df.index.get_level_values('Nation').str.startswith('U')])
          Z
Nation A   
Uw     2  4
Ur     5  6
Share:
38,729

Related videos on Youtube

Oduvan
Author by

Oduvan

Updated on May 15, 2022

Comments

  • Oduvan
    Oduvan 13 days

    In dataframe I have an index from column Nation.

    But I can't do

    df[df.Nation.str.startswith('U')]
    

    without reseting index.

    How can I get str object of index?