简体   繁体   English

在第一级多索引中查询带有整数的熊猫数据框

[英]query pandas dataframe with integer in first level of multiindex

I'm having trouble with pandas MultiIndex, if the first index is an integer. 如果第一个索引是整数,我会遇到熊猫MultiIndex问题。 I could not find this question, so maybe I'm doing something wrong here? 我找不到这个问题,所以也许我在这里做错了吗?

I use pandas version '0.16.2' 我使用的是熊猫版本“ 0.16.2”

Example: 例:

in: 在:

data2 = pd.DataFrame(np.random.rand(10), 
                index = [['a','a','a','a','b','b','b','b','c','c'],
                         [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 0]])
data2.ix[['b','c']]

out: 出:

            0
b 5  0.295579
  6  0.691801
  7  0.386504
  8  0.602777
c 9  0.269147
  0  0.029509

but with integers in the first index-level it doesn't seem to work: 但是在第一个索引级别使用整数似乎不起作用:

data = pd.DataFrame(np.random.rand(10), 
                index = [[ 1 , 1 , 1 , 1 , 2 , 2 , 2 , 2 , 3 , 3], 
                         ['a','b','c','d','e','f','g','h','i','j']])
data.ix[[2,3]] 

out: 出:

        0
1 c  0.437728
  d  0.785359

Use loc instead of ix : 使用loc代替ix

data = pd.DataFrame(np.random.rand(10), 
                index = [[ 1 , 1 , 1 , 1 , 2 , 2 , 2 , 2 , 3 , 3], 
                         ['a','b','c','d','e','f','g','h','i','j']])
data.loc[[2,3]] 

In [264]: data.loc[[2,3]]
Out[264]: 
            0
2 e  0.846643
  f  0.200234
  g  0.298223
  h  0.766459
3 i  0.860181
  j  0.980182

For ix it's strange why it's not working because from docs : 对于ix,奇怪的是为什么它不起作用,因为来自docs

However, when an axis is integer based, ONLY label based access and not positional access is supported Thus, in such cases, it's usually better to be explicit and use .iloc or .loc. 但是,当轴基于整数时,仅支持基于标签的访问,而不支持位置访问。因此,在这种情况下,通常最好显式并使用.iloc或.loc。

You index values are integer so they are should be analysed as labels: 您的索引值是整数,因此应将其作为标签进行分析:

In [271]: data.index.levels[0]
Out[271]: Int64Index([1, 2, 3], dtype='int64') 

But they recommended to use loc in such cases to be more explicit. 但是他们建议在这种情况下使用loc以便更明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM