Python:来自 2 个数组的直方图/合并数据。

Python: histogram/ binning data from 2 arrays.

我有两个数据数组:一个是半径值,另一个是该强度下的相应强度读数:

例如一小部分数据。第一列是半径,第二列是强度。

29.77036614 0.04464427 29.70281027 0.07771409 29.63523525 0.09424901 29.3639355 1.322793 29.29596385 2.321502 29.22783249 2.415751 29.15969437 1.511504 29.09139827 1.01704 29.02302068 0.9442765 28.95463729 0.3109002 28.88609766 0.162065 28.81754446 0.1356054 28.74883612 0.03637681 28.68004928 0.05952569 28.61125036 0.05291172 28.54229804 0.08432806 28.4732599 0.09950128 28.43877462 0.1091304 28.40421016 0.09629156 28.36961249 0.1193614 28.33500089 0.102711 28.30037503 0.07161685

如何对半径数据进行分箱,并找到与该分箱半径相对应的平均强度。

这样做的目的是然后使用平均强度将强度值分配给具有缺失 (NaN) 数据点的半径数据。

我以前从未使用过直方图函数,对它们的工作原理知之甚少/如果可能的话。完整的数据集很大,有 336622 个数据点,所以我真的不想使用循环或 if 语句来实现这一点。
非常感谢您的帮助。

如果你只需要为少数几个点做这件事,你可以这样做。

如果 intensitesradius 是您的数据的 numpy 数组:

bin_width = 0.1 # Depending on how narrow you want your bins

def get_avg(rad):
    average_intensity = intensities[(radius>=rad-bin_width/2.) & (radius<rad+bin_width/2.)].mean()
    return average_intensities

# This will return the average intensity in the bin: 27.95 <= rad < 28.05
average = get_avg(28.)

这并不是真正对您所追求的进行直方图绘制。直方图更多地是对落入特定容器的项目的计数。您想要做的更多是按操作分组,您可以按半径间隔对强度进行分组,并在强度组上应用一些聚合方法,如平均值或中位数等。

但是,您所描述的内容听起来更像是您想执行的某种插值。所以我建议考虑将插值作为解决问题的替代方法。不管怎样,这里有一个建议,你可以如何实现你所要求的(假设你可以使用 numpy)——我使用随机输入来说明:

radius = numpy.fromiter((random.random() * 10 for i in xrange(1000)), dtype=numpy.float)
intensities = numpy.fromiter((random.random() * 10 for i in xrange(1000)), dtype=numpy.float)
# group your radius input into 20 equal distant bins
bins = numpy.linspace(radius.min(), radius.max(), 20)
groups = numpy.digitize(radius, bins)
# groups now holds the index of the bin into which radius[i] falls
# loop through all bin indexes and select the corresponding intensities
# perform your aggregation on the selected intensities
# i'm keeping the aggregation for the group in a dict
aggregated = {}
for i in range(len(bins)+1):
    selected_intensities = intensities[groups==i]
    aggregated[i] = selected_intensities.mean()