我得到了以下熊猫DataFrame:

     bucket             value
0   (15016, 18003.2]    368
1   (12028.8, 15016]    132
2   (18003.2, 20990.4]  131
3   (9041.6, 12028.8]   116
4   (50.128, 3067.2]    82
5   (3067.2, 6054.4]    79
6   (6054.4, 9041.6]    54
7   (20990.4, 23977.6]  28
8   (23977.6, 26964.8]  8
9   (26964.8, 29952]    2


buckets已使用pd.cut()命令计算(dtype为cateogry

我想检查一个值,例如my_value = 20000,是否在bucket的范围之一内。

它可能会返回一个包含另外一列的数据框:

     bucket             value   value_in_bucket
0   (15016, 18003.2]    368     FALSE
1   (12028.8, 15016]    132     FALSE
2   (18003.2, 20990.4]  131     TRUE
3   (9041.6, 12028.8]   116     FALSE
4   (50.128, 3067.2]    82      FALSE
5   (3067.2, 6054.4]    79      FALSE
6   (6054.4, 9041.6]    54      FALSE
7   (20990.4, 23977.6]  28      FALSE
8   (23977.6, 26964.8]  8       FALSE
9   (26964.8, 29952]    2       FALSE


主要问题是bucket的每个项目都是一个字符串,因此我可以将字符串分成两列,并使用基本测试和apply,但对我来说似乎不太好。

最佳答案

您可以在pd.cut()列上使用相同的bin(或更好的是,当使用bucket参数创建retbins=True列时作为@ayhan suggested保存容器,更好地应用value)并将其与bucket列进行比较。

演示:

In [265]: df = pd.DataFrame(np.random.randint(1,20, 5), columns=list('a'))

In [266]: df
Out[266]:
    a
0   9
1   6
2  13
3  11
4  17


创建bucket列并一步保存箱:

In [267]: df['bucket'], bins = pd.cut(df.a, bins=5, retbins=True)

In [268]: df
Out[268]:
    a        bucket
0   9   (8.2, 10.4]
1   6  (5.989, 8.2]
2  13  (12.6, 14.8]
3  11  (10.4, 12.6]
4  17    (14.8, 17]

In [269]: bins
Out[269]: array([  5.989,   8.2  ,  10.4  ,  12.6  ,  14.8  ,  17.   ])


生成一个我们想要比较的新列:

In [270]: df['b'] = np.random.randint(10,12, 5)

In [271]: df
Out[271]:
    a        bucket   b
0   9   (8.2, 10.4]  10
1   6  (5.989, 8.2]  11
2  13  (12.6, 14.8]  11
3  11  (10.4, 12.6]  11
4  17    (14.8, 17]  11


比较我们是否有匹配项(使用保存的bins):

In [272]: pd.cut(df.b, bins=bins) == df.bucket
Out[272]:
0     True
1    False
2    False
3     True
4    False
dtype: bool

关于python - 检查值是否在 float 范围的分类序列中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38850859/

10-12 14:35