【发布时间】:2013-12-20 06:18:45
【问题描述】:
我有两个对应的二维数组,一个是速度,一个是强度。强度值与每个速度元素相匹配。
我创建了另一个一维数组,该数组在均匀的 bin 宽度下从最小速度到最大速度。
如何将我的 2d 数组中的强度值求和,这些值对应于我的 1d 数组中的速度箱。
例如:如果我有 I = 5 对应于速度 = 101km/s,那么这将被添加到 bin 100 - 105 km/s。
这是我的意见:
rad = np.linspace(0, 3, 100) # polar coordinates
phi = np.linspace(0, np.pi, 100)
r, theta = np.meshgrid(rad, phi) # 2d arrays of r and theta coordinates
V0 = 225 # Velocity function w/ constants.
rpe = 0.149
alpha = 0.003
Vr = V0 * (1 - np.exp(-r / rpe)) * (1 + (alpha * np.abs(r) / rpe)) # returns 100x100 array of Velocities.
Vlos = Vr * np.cos(theta)# Line of sight velocity assuming the observer is in the plane of the polar disk.
a = (r**2) # intensity as a function of radius
b = (r**2 / 0.23)
I = (3.* np.exp(-1. * a)) - (1.8 * np.exp(-1. * b))
我希望首先创建从 Vmin 到 Vmax 的速度箱,然后对每个箱的强度求和。
我想要的输出将类似于
V_bins = [0, 5, 10,... Vlos.max()]
I_sum = [1.4, 1.1, 1.8, ... 1.2]
plot(V_bins, I_sum)
编辑:我想出了临时解决方案,但也许有更优雅/更有效的方法来实现它?
两个数组 Vlos 和 I 都是 100 x 100 矩阵。
Vlos = array([[ 0., 8.9, 17.44, ..., 238.5],...,
[-0., -8.9, -17.44, ..., -238.5]])
I = random.random((100, 100))
V = np.arange(Vlos.min(), Vlos.max()+5, 5)
bins = np.zeros(len(V))
for i in range(0, len(V)-1):
for j in range(0, len(Vlos)): # horizontal coordinate in matrix
for k in range(0, len(Vlos[0])): # vert coordinate
if Vlos[j,k] >= V[i]and Vlos[j,k] < V[i+1]:
bins[i] = bins[i] + I[j,k]
结果如下图所示。 直方图中的整体形状是可以预料的,但是我不明白 V = 0 处曲线的尖峰。据我所知,这在数据中不存在,这导致我质疑我的方法。
任何进一步的帮助将不胜感激。
【问题讨论】:
-
1.你尝试了什么? 2. 请举例说明你正在尝试做什么,否则很难理解。
-
您正在寻找的是interval tree。请参阅this answer 了解更多信息。
-
请提供生成示例输入的代码,并尽可能准确地编写所需的输出。
-
我已经添加了对我的代码和所需输出的一些解释,希望这会有所帮助。
标签: python arrays numpy indexing sum