我在 Pandas DataFrame 中有字符串索引如何通过开始选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41536343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:45:04  来源:igfitidea点击:

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

pythonpandas

提问by Oduvan

In dataframe I have an index from column Nation.

在数据框中,我有一个来自 Nation 列的索引。

But I can't do

但我做不到

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

without reseting index.

无需重置索引。

How can I get str object of index?

如何获取索引的 str 对象?

回答by jezrael

Use indexwhich works with strnice:

使用index它与strnice 一起使用:

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 levelof MultiIndexuse get_level_values:

如果需要通过选择levelMultiIndex使用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