【问题标题】:How to create a numpy array filled with average value of a vector如何创建一个填充向量平均值的numpy数组
【发布时间】:2021-10-21 02:10:06
【问题描述】:

我不知道如何更好地表达我的问题。基本上,我有三个相同长度的列表xyz,我想用相关 z 值的平均值填充 z/y 平面中的 2D numpy 数组。

以下是我可以实现的目标:

import numpy as np
import matplotlib.pyplot as plt

x = [37.59390426045407, 38.00530354847739, 38.28412244348653, 38.74871247986305, 38.73175910429809, 38.869008864244016, 39.188234404976555, 39.92835838352555, 40.881394113153334, 41.686136269465884]
y = [0.1305391767832006, 0.13764519613447768, 0.14573326951792354, 0.15090729309032114, 0.16355823707239897, 0.17327106424274763, 0.17749746339532224, 0.17310384614773594, 0.16545780437882962, 0.1604752704890856]
z = [0.05738534353865021, 0.012572155256903583, -0.021709582561809437, -0.11191337750722108, -0.07931921785775153, -0.06241610118871843, 0.014216349927058225, 0.042002641153291886, -0.029354425271534645, 0.061894011359833856]

n = 5
image = np.zeros(shape=(n,n))

# Fill the 2D array
x0 = min(x)
y0 = min(y)
dx = (max(x) - min(x))/n
dy = (max(y) - min(y))/n
# Loop over each 2D cell
for index_x in range(n):
    for index_y in range(n):
        # find the limits of the cell 
        x1 = x0 + index_x * dx
        x2 = x0 + (index_x+1) * dx
        y1 = y0 + index_y * dy
        y2 = y0 + (index_y+1) * dy
        # find the points of z that lie within the range of the cell
        vec_z = [z[idx] for idx in range(len(z)) if x[idx]>=x1 and x[idx]<x2 and y[idx]>=y1 and y[idx]<y2]
        if vec_z:
            image[index_x, index_y] = np.mean(vec_z)

# In the end, used to create a surface plot
fig, ax = plt.subplots()
ax.imshow(image, cmap=plt.cm.gray, interpolation='nearest')
plt.show()

有没有更简单的方法来实现这一点?我可以想象有一个numpy 方法。

【问题讨论】:

  • 实际上您只是想对数据进行分箱并用平均值填充箱,但您不在乎这些箱在哪里?例如在您的示例中,您使用 n=5 并且在最小值和最大值之间平均分配...
  • 仅供参考:彻底回答问题非常耗时。如果您的问题已解决,请通过接受最适合您的需求的解决方案表示感谢。 位于答案左上角的 / 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您也可以使用 / 箭头对答案的有用性进行投票。 如果解决方案不能回答问题,请发表评论What should I do when someone answers my question?。谢谢

标签: python numpy matplotlib math data-visualization


【解决方案1】:

如果我正确理解您想要做什么,也许scipy.interpolate.interp2d 的 2D 插值就是您正在寻找的。
您定义点的插值函数:

f = interp2d(x = x, y = y, z = z)

然后定义XY 网格:

N = 50
x_axis = np.linspace(np.min(x), np.max(x), N)
y_axis = np.linspace(np.min(y), np.max(y), N)

X, Y = np.meshgrid(x_axis, y_axis)

最后你可以在网格网格上计算Z 插值:

Z = np.zeros((N, N))
for i in range(N):
    for j in range(N):
        Z[i, j] = f(X[i, j], Y[i, j])

如果您在 3D 中绘制插值曲面,您会得到:

fig = plt.figure()
ax = fig.add_subplot(projection = '3d')

ax.plot_surface(X, Y, Z, cmap = 'jet', shade = False)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()

与插值数据点相比的插值表面:

ax.scatter(x, y, z, color = 'black', s = 100, alpha = 1)

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2020-02-18
    • 2017-08-15
    • 2018-01-16
    • 1970-01-01
    相关资源
    最近更新 更多