【问题标题】:Summing one array in terms of another - python用另一个数组求和一个数组 - python
【发布时间】: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


【解决方案1】:
import numpy as np
bins = np.arange(100,120,5)
velocities = np.array([101, 111, 102, 112])
intensities = np.array([1,2,3,4])
h = np.histogram(velocities, bins, weights=intensities)
print h

输出:

(array([4, 0, 6]), array([100, 105, 110, 115]))

【讨论】:

  • 如果我知道如何使用相应的速度对强度求和,我可以使用这种方法。有没有一种方法(可能使用索引?)相对于速度数组对强度数组的元素求和。
  • 这就是直方图的作用。如果你想要别的东西,请给我们看一个具体的例子,输入和输出数字。添加方程式会让我们更难。
猜你喜欢
  • 2010-12-29
  • 2021-12-03
  • 2018-12-25
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多