python - 检查值是否在浮点范围的分类系列中

标签 python pandas dataframe categories

我得到了以下 pandas 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

存储桶已使用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() 使用相同的垃圾箱(或者更好的是,在创建存储桶时使用 @ayhan suggested 保存垃圾箱) > 列,在 value 列上使用 retbins=True 参数),并将其与 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

一步创建存储桶列并保存存储桶:

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 - 检查值是否在浮点范围的分类系列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38850859/

相关文章:

python - 蒙蒂霍尔模拟器有一个错误的结果

python - 将 3d 数组中的特定列复制到 2d 数组 [Python/Pygame]

python - 如何在python数据表中填充空值?

pandas - 当列是列表或集合时,重新映射 Pandas 列中的值

python - 根据数据框中的其他值更改 pandas 数据框的值

python - Pandas 按降序枚举组

python - python中Tan的逆(tan-1)

python - 当我运行 'pip install something' 时,pip 从哪里获取这个东西?

python - 使用 Pandas 转换年度数据

python - 从多索引数据框中选择列,例如制作直方图