Reputation: 439
I have a dataset with only two columns. I would like to extract a small part out of it based on some condition on one column. Consider this as my dataset.
A B
1 10
1 9
2 11
3 12
3 11
4 9
Suppose I want to extract only those rows which have values in B from 10 - 12. so I would get a new dataset as:
A B
1 10
2 11
3 12
3 11
I tried using df.loc[df["B"] == range(10, 12)] but it dose not work, can someone help me with this?
Upvotes: 1
Views: 1694
Reputation: 1795
Here's one more (not using .loc()
or .query()
) which looks more like the initial (unsuccessful) attempt:
df[df.B.isin(range(10,13))]
Upvotes: 0
Reputation: 76917
You can use .between
In [1031]: df.loc[df.B.between(10, 12)]
Out[1031]:
A B
0 1 10
2 2 11
3 3 12
4 3 11
Or, isin
In [1032]: df.loc[df.B.isin(range(10, 13))]
Out[1032]:
A B
0 1 10
2 2 11
3 3 12
4 3 11
Or, query
In [1033]: df.query('10 <= B <= 12')
Out[1033]:
A B
0 1 10
2 2 11
3 3 12
4 3 11
Or, good'ol boolean
In [1034]: df.loc[(df.B >= 10) & (df.B <= 12)]
Out[1034]:
A B
0 1 10
2 2 11
3 3 12
4 3 11
Upvotes: 6