我有一个通过以下代码行以元组形式表示的 2 变量离散函数:
hist_values, hist_x, hist_y = np.histogram2d()
您可以在哪里想到一个非光滑的 3d 表面,其中hist_values是边缘坐标为 ( hist_x , hist_y ) 的网格处的表面高度。
现在,我想收集hist_values高于某个阈值水平的那些网格。
我有一个通过以下代码行以元组形式表示的 2 变量离散函数:
hist_values, hist_x, hist_y = np.histogram2d()
您可以在哪里想到一个非光滑的 3d 表面,其中hist_values是边缘坐标为 ( hist_x , hist_y ) 的网格处的表面高度。
现在,我想收集hist_values高于某个阈值水平的那些网格。
您可以简单地将hist_values
与进行比较,这将为您提供一个掩码作为可用于切片threshold
的数组,例如:bool
import numpy as np
# prepare random input
arr1 = np.random.randint(0, 100, 1000)
arr2 = np.random.randint(0, 100, 1000)
# compute 2D histogram
hist_values, hist_x, hist_y = np.histogram2d(arr1, arr2)
mask = hist_values > threshold # the array of `bool`
hist_values[mask] # only the values above `threshold`
当然,这些值随后会被收集到一个扁平化的数组中。或者,您也可以mask
用来实例化一个掩码数组对象(使用numpy.ma
,请参阅文档以获取更多信息)。
如果您在发生这种情况的坐标之后,您应该使用numpy.where()
.
# i0 and i1 contain the indices in the 0 and 1 dimensions respectively
i0, i1 = np.where(hist_values > threshold)
# e.g. this will give you the first value satisfying your condition
hist_values[i0[0], i1[0]]
对于 和 的相应值,hist_x
您hist_y
应该注意这些是箱的边界,而不是例如中间值,因此您可以求助于它的下限或上限。
# lower edges of `hist_x` and `hist_y` respectively...
hist_x[i0]
hist_y[i1]
# ... and upper edges
hist_x[i0 + 1]
hist_y[i1 + 1]