0

I have the below sample df, and I'd like to select all the rows that are between a range of values in a specific column:

          0       1       2     3     4     5  index
0   -252.44 -393.07  886.72 -2.04  1.58 -2.41      0
1   -260.25 -415.53  881.35 -3.07  0.08 -1.66      1
2   -267.58 -412.60  893.07 -2.98 -1.15 -2.66      2
3   -279.30 -417.97  880.86 -1.15 -0.50 -1.37      3
4   -252.93 -395.51  883.30 -1.30  1.43  4.17      4

I'd like to get the below df (all the rows between index value of 1-3):

          0       1       2     3     4     5  index
1   -260.25 -415.53  881.35 -3.07  0.08 -1.66      1
2   -267.58 -412.60  893.07 -2.98 -1.15 -2.66      2
3   -279.30 -417.97  880.86 -1.15 -0.50 -1.37      3

How can I do it?

I tried the below which didn't work:

new_df = df[df['index'] >= 1 & df['index'] <= 3]

1 Answer 1

1

Between min and max: use between():

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1,2,3], 'b':[11,12,13]})
>>> df
   a   b
0  1  11
1  2  12
2  3  13

>>> df[df.a.between(1,2)]
   a   b
0  1  11
1  2  12

Your attempt new_df = df[df['index'] >= 1 & df['index'] <= 3] is wrong in two places:

  • it's df.index, not df["index"]
  • when using multiple filters, use parentheses: df[(df.index >= 1) & (df.index <= 3)]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.