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?
To select the rows, the syntax is df. loc[start:stop:step] ; where start is the name of the first-row label to take, stop is the name of the last row label to take, and step as the number of indices to advance after each extraction; for example, you can use it to select alternate rows.
Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc. Indexing in Pandas means selecting rows and columns of data from a Dataframe.
Using “contains” to Find a Substring in a Pandas DataFrame The contains method in Pandas allows you to search a column for a specific substring. The contains method returns boolean values for the Series with True for if the original Series value contains the substring and False if not.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With