在 Pandas 数据框中通过多索引选择(子集)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23464273/
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-13 22:00:19  来源:igfitidea点击:

Selecting (subsetting) by multi index in pandas dataframe

pythonpandassubsetdataframe

提问by user3576212

I was wondering if there is a clean way of selecting or subsetting a Pandas dataframe based on multi index. My data looks like this (id and date are index):

我想知道是否有一种干净的方法可以基于多索引选择或子集 Pandas 数据帧。我的数据是这样的(id 和 date 是索引):

                        values                  
id     date
10113  2010-07-21      24.7000
       2010-07-22      25.2600  
       2010-07-23      25.2800  
       2010-07-26      25.3700 
       2010-07-27      25.2900 
10223  2011-07-21      24.7000
       2011-07-22      25.2600  
       2011-07-23      25.2800  
       2011-07-26      25.3700 
       2011-07-27      25.2900 

I want something like this:

我想要这样的东西:

df.xs[10223).xs('2011-07-21':'2011-07-30')

but above code doesn't work for the second xs(). xs()can only select a single row, not a subset of dataframe. I also tried df.query()and df.ix(), but no luck.

但上面的代码不适用于第二个xs()xs()只能选择一行,而不是数据帧的子集。我也试过df.query()and df.ix(),但没有运气。

Thanks for your help!

谢谢你的帮助!

回答by Karl D.

You should be able to use .xsor .ixin the following way:

您应该能够以下列方式使用.xs.ix

print df.ix[(10223,'2011-07-21'):(10223,'2011-07-30')]

                 values
id    date              
10223 2011-07-21   24.70
      2011-07-22   25.26
      2011-07-23   25.28
      2011-07-26   25.37
      2011-07-27   25.29

print df.xs(10223,level='id')

            values
date              
2011-07-21   24.70
2011-07-22   25.26
2011-07-23   25.28
2011-07-26   25.37
2011-07-27   25.29

See herefor more information

请参阅此处了解更多信息