我想知道是否存在将直方图反转回强度信号的numpythonic方式。
例如:
>>> A = np.array([7, 2, 1, 4, 0, 7, 8, 10])
>>> H, edge = np.histogram(A, bins=10, range=(0,10))
>>> np.sort(A)
[ 0 1 2 4 7 7 8 10]
>>> H
[1 1 1 0 1 0 0 2 1 1]
>>> edge
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
有没有办法使用A
和H
重建原始edge
强度?当然,位置信息会丢失,但我只想恢复强度和相对出现次数。
我有这种循环的方式:
>>> reco = []
>>> for i, h in enumerate(H):
... for _ in range(h):
... reco.append(edge[i])
...
>>> reco
[0.0, 1.0, 2.0, 4.0, 7.0, 7.0, 8.0, 9.0]
# I've done something wrong with the right-most histogram bin, but we can ignore that for now
对于大直方图,循环方式效率低下。是否有我在循环中所做的矢量化等价物? (我的直觉说numpy.digitize
将涉及......)
答案 0 :(得分:3)
当然,您可以使用np.repeat
:
import numpy as np
A = np.array([7, 2, 1, 4, 0, 7, 8, 10])
counts, edges = np.histogram(A, bins=10, range=(0,10))
print(np.repeat(edges[:-1], counts))
# [ 0. 1. 2. 4. 7. 7. 8. 9.]
显然,无法恢复bin中值的确切位置,因为在生成直方图的过程中会丢失该信息。您可以使用较低或较高的bin边缘(如上例所示),也可以使用中心值,例如:
print(np.repeat((edges[:-1] + edges[1:]) / 2., counts))
# [ 0.5 1.5 2.5 4.5 7.5 7.5 8.5 9.5]