根据pandas中另一列中的值间隔,选择列中的值范围

时间:2017-07-18 09:18:48

标签: python pandas

我有一个数据框:

scale    year       value
-10      2017       1 252
-9       2017       1 011
-8       2017         921
-7       2017       1 161
-6       2017       1 331
-5       2017       1 133
-4       2017         899
-3       2017       1 063
-2       2017       1 320
-1       2017       1 201
 0       2017       1 212
 1       2017       1 543
 2       2017         656
 3       2017         443
 4       2017       1 398
 5       2017       1 776
...

我需要在value列中选择与scale列中的值范围相对应的值,其中scale位于0-7之间。在示例中,它将是1 2121 161的值。

关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:2)

boolean indexing使用between

df = df[df['scale'].between(-7,0)]
print (df)
    scale  year  value
3      -7  2017  1 161
4      -6  2017  1 331
5      -5  2017  1 133
6      -4  2017    899
7      -3  2017  1 063
8      -2  2017  1 320
9      -1  2017  1 201
10      0  2017  1 212

答案 1 :(得分:2)

我们也可以使用.query方法:

In [39]: df.query("-7 <= scale <= 0")
Out[39]:
    scale  year  value
3      -7  2017  1 161
4      -6  2017  1 331
5      -5  2017  1 133
6      -4  2017    899
7      -3  2017  1 063
8      -2  2017  1 320
9      -1  2017  1 201
10      0  2017  1 212