pandas:使用.loc选择索引标签数组

cd9*_*d98 6 python pandas

考虑一下这个dataFrame:

df = pd.DataFrame({u'A': {2.0: 2.2,
  7.0: 1.4,
  8.0: 1.4,
  9.0: 2.2},  u'B': {2.0: 7.2,
  7.0: 6.3,
  8.0: 4.4,
  9.0: 5.0}})
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

      A       B
2    2.2     7.2
7    1.4     6.3
8    1.4     4.4
9    2.2     5.0
Run Code Online (Sandbox Code Playgroud)

我想得到带标签的索引27(数字,而不是字符串)

df.loc[[2, 7]]
Run Code Online (Sandbox Code Playgroud)

给出错误!

IndexError: indices are out-of-bounds
Run Code Online (Sandbox Code Playgroud)

然而,df.loc[7]df.loc[2]做工精细,并符合预期.另外,如果我用字符串而不是数字定义数据框索引:

df2 = pd.DataFrame({u'A': {'2': 2.2,
  '7': 1.4,
  '8': 1.4,
  '9': 2.2},
 u'B': {'2': 7.2,
  '7': 6.3,
  '8': 4.4,
  '9': 5.0}})

df2.loc[['2', '8']]
Run Code Online (Sandbox Code Playgroud)

它工作正常.

这不是我期望的行为df.loc(它是一个bug还是只是一个陷阱?)我可以将一组数字作为标签索引传递而不仅仅是位置吗?

我可以将所有索引转换为字符串,然后进行操作,.loc但对我的其余代码来说非常不方便.

谢谢你的时间!

Jef*_*eff 7

这是0.12中的错误.版本0.13修复此问题(IOW,标签选择,当您传递列表时,数字或字符串是否应该起作用).

可以这样做(虽然使用内部方法):

In [10]: df.iloc[df.index.get_indexer([2,7])]
Out[10]: 
     A    B
2  2.2  7.2
7  1.4  6.3
Run Code Online (Sandbox Code Playgroud)