Pandas 在布尔索引中使用行标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14725068/
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
Pandas using row labels in boolean indexing
提问by jason
So I have a DataFrame like this:
所以我有一个像这样的数据帧:
df = pd.DataFrame(np.random.randn(6, 3), columns=['a', 'b', 'c'])
a b c
0 1.877317 0.109646 1.634978
1 -0.048044 -0.837403 -2.198505
2 -0.708137 2.342530 1.053073
3 -0.547951 -1.790304 -2.159123
4 0.214583 -0.856150 -0.477844
5 0.159601 -1.705155 0.963673
We can boolean index it like this
我们可以像这样布尔索引它
df[df.a > 0]
a b c
0 1.877317 0.109646 1.634978
4 0.214583 -0.856150 -0.477844
5 0.159601 -1.705155 0.963673
We can also slice it via row labels like this:
我们也可以像这样通过行标签对其进行切片:
df.ix[[0,2,4]]
a b c
0 1.877317 0.109646 1.634978
2 -0.708137 2.342530 1.053073
4 0.214583 -0.856150 -0.477844
I would like to do both these operations at the same time (So I avoid making an unnecessary copy just to do the row label filter). How would I go about doing it?
我想同时执行这两个操作(因此我避免为了执行行标签过滤器而制作不必要的副本)。我将如何去做?
Pseudo code for what I am looking for:
我正在寻找的伪代码:
df[(df.a > 0) & (df.__index__.isin([0,2,4]))]
采纳答案by Andy Hayden
You nearly had it:
你几乎拥有它:
In [11]: df[(df.a > 0) & (df.index.isin([0, 2, 4]))]
Out[11]:
a b c
0 1.877317 0.109646 1.634978
4 0.214583 -0.856150 -0.477844

