I have a row index in a pandas DataFrame, how can I select using startswith?

In a dataframe, I have an index from a Nation column.

But I can not do

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

without rewrite index.

How can I get an index str object?

+4
source share
1 answer

Use indexthat works with strnice:

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

Example:

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 you need to choose levelof 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
+7
source

Source: https://habr.com/ru/post/1666169/


All Articles