Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用np.where在多个数组中循环_Python_Loops_Numpy - Fatal编程技术网

Python 使用np.where在多个数组中循环

Python 使用np.where在多个数组中循环,python,loops,numpy,Python,Loops,Numpy,我有两个列表:距离、边界和距离 distance_boundary = [100,200,300] distance = [125,255,285,140,160,180] 现在我想创建一个新变量floor,我想根据距离值为floor赋值,该值由距离_边界定义 比如说, distance[0] is 125 因为这是距离_边界[0]和距离_边界[1]之间的距离 因此,楼板的相应值应为1 distance[1] is 255 因为这是距离_边界[1]和距离_边界[2]之间的距离 因此,楼层的

我有两个列表:距离、边界和距离

distance_boundary = [100,200,300]
distance = [125,255,285,140,160,180]
现在我想创建一个新变量floor,我想根据距离值为floor赋值,该值由距离_边界定义

比如说,

distance[0] is 125
因为这是距离_边界[0]和距离_边界[1]之间的距离 因此,楼板的相应值应为1

distance[1] is 255
因为这是距离_边界[1]和距离_边界[2]之间的距离 因此,楼层的相应值应为2

通过这个循环应该可以得到floor的最终值

floor = [1,2,2,1,1,1]
我试着在距离中循环,并习惯于np.where来分配任务

floor = []

for j in range(0,len(distance)):

    floor = (np.where((distance[j]>distance_boundary[0]) & (distance[j]>distance_boundary[1]))
                      ,1,2)
    floor.append(floor)
这并没有给我期望的结果,而且它看起来不可扩展。
是否有其他更好的解决方案

使用
pandas.cut

import pandas as pd

distance_boundary = [100,200,300]
distance = [125,255,285,140,160,180]

[distance_boundary.index(i.right) for i in pd.cut(distance, distance_boundary)]
输出:

[1, 2, 2, 1, 1, 1]
您可以尝试以下方法:

将numpy导入为np
距离_边界=np.数组([100200300])
距离=np.数组([125255285140160180])
地板=np.类零(距离)
标志=(距离>100)和(距离<200)
楼层[旗帜]=1
标志=(距离>200)和(距离<300)
楼层[旗帜]=2
印刷品(地板)
>>>[1 2 2 1 1 1]

您可以使用迭代方法。使用
distance\u boundary
中的每个值作为阈值,对二进制阈值的结果求和:

import numpy as np

distance_boundary = np.array([100,200,300])
distance = np.array([125,255,285,140,160,180])

print(sum(np.where(distance > i, 1, 0) for i in distance_boundary))
这将打印:

[1 2 2 1 1 1]
O(N日志N)解决方案:

    from bisect import bisect_left

    def binarySearch(num, arr):
        i = bisect_left(arr, num)
        if arr[i] == num:
            return i+1
        else:
            return i


    distance_boundary = [100,200,300]
    distance = [125,255,285,140,160,180]

    floor = list()
    for num in distance:
        floor.append(binarySearch(num, distance_boundary))

    print("floor =", floor)
似乎就是你要找的:

np.searchsorted(distance_boundary, distance)
# array([1, 2, 2, 1, 1, 1])

如果您的边界始终是100的倍数,则可以:

代码:

输出:


np.where中的条件需要修改为
np.where(距离[j]>distance_边界[0]和距离[j]谢谢Paul,这就是我要寻找的。一个函数解:)它实际上是以相反的方式工作的和(np.where(压力[q//100表示距离为q]
的速度,这也适用于非10次幂的数字。
[int(str(q)[0:-2]) for q in distance]
[1, 2, 2, 1, 1, 1]