繁体   English   中英

基于浮点数组将2D numpy数组中的列广播到更大的2D数组

[英]Broadcasting columns from a 2D numpy array to a larger 2D array based on an array of floats

我不太清楚如何这样说,所以我会尽量在我的描述中说清楚。 现在我有一个3D numpy数组,其中第1列代表深度,第2列代表x轴。 我的目标是根据1D浮点数组中的值,在x轴上展开列。

这是它变得棘手的地方,我只有点之间的相对距离。 也就是说,列1和列2之间的距离等等。

这是我拥有的和我想要的一个例子:

darray = [[2  3  7  7]
          [4  8  2  3]
          [6  1  9  5]
          [3  4  8  4]]

posarray = [ 3.767, 1.85, 0.762]

DesiredArray = [[2  0  0  0  3  0  7  7]
                [4  0  0  0  8  0  2  3]
                [6  0  0  0  1  0  9  5]
                [3  0  0  0  4  0  8  4]]

我是如何尝试实现它的:

def space_set(darr, sarr):
    spaced = np.zeros((260,1+int(sum(sarr))), dtype = float)
    x = 0
    for point in range(len(sarr)):
            spaced[:, x] = darr[:,point]
            x = int(sum(sarr[0:point]))
    spaced[:,-1] = darr[:,-1]

然后我计划使用matplotlibs pcolor绘制它。 这种方法似乎失去了列。 有关直接绘制或制作numpy数组的想法吗? 提前致谢。

这是我正在寻找的一个例子。 示例图片

由于有太多的空白,也许绘制矩形更容易,而不是使用pcolor 作为奖励,您可以将矩形准确放置在您想要的位置,而不必将它们“捕捉”到整数值网格。 并且,您不必为主要填充零的较大2D阵列分配空间。 (在你的情况下,所需的内存可能是微不足道的,但这个想法不能很好地扩展,所以如果我们可以避免这样做,那就太好了。)

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
import matplotlib.cm as cm

def draw_rect(x, y, z):
    rect = patches.Rectangle((x,y), 1, 1, color = jet(z))
    ax.add_patch(rect)

jet = plt.get_cmap('jet')
fig = plt.figure()
ax = fig.add_subplot(111)

darray = np.array([[2, 3, 7, 7],
                   [4, 8, 2, 3],
                   [6, 1, 9, 5],
                   [3, 4, 8, 4]], dtype = 'float')
darray_norm = darray/darray.max()

posarray = [3.767, 1.85, 0.762]
x = np.cumsum(np.hstack((0, np.array(posarray)+1)))

for j, i in np.ndindex(darray.shape):
    draw_rect(x[j], i, darray_norm[i, j])
ax.set_xlim(x.min(),x.max()+1)
ax.set_ylim(0,len(darray))
ax.invert_yaxis()    
m = cm.ScalarMappable(cmap = jet)
m.set_array(darray)
plt.colorbar(m)
plt.show()

产量

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM