OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Pandas using both row labels and boolean indexing in the same expression

  • Thread starter Thread starter jason
  • Start date Start date
J

jason

Guest
So I have a DataFrame like this:

Code:
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

Code:
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:

Code:
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:

Code:
df[(df.a > 0) & (df.__index__.isin([0,2,4]))]
<p>So I have a DataFrame like this: </p>

<pre><code>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
</code></pre>

<p>We can boolean index it like this </p>

<pre><code>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
</code></pre>

<p>We can also slice it via row labels like this: </p>

<pre><code>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
</code></pre>

<p>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? </p>

<p>Pseudo code for what I am looking for: </p>

<pre><code>df[(df.a > 0) & (df.__index__.isin([0,2,4]))]
</code></pre>
 
Top