Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

python - Pandas using row labels in boolean indexing

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]))] 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...