微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在网格数据图中提取数据的python函数

如何解决在网格数据图中提取数据的python函数

我有以下代码和情节:

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
def func(x,y):
    return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
grid_x,grid_y = np.mgrid[0:1:200j,0:1:200j]
rng = np.random.default_rng()
points = rng.random((1000,2))
values = func(points[:,0],points[:,1])
grid_z = griddata(points,values,(grid_x,grid_y),method='linear')
plt.xlabel("degrees")
plt.ylabel("degrees")
plt.imshow(grid_z,extent=(-0.5,0.5,-0.5,0.5),origin='lower')

我想提取以上图为中心、半径为 0.25° 的圆形区域内所有点的平均值。

感谢您的帮助

解决方法

您需要的第一件事是圈子的布尔掩码。 然后您可以将其应用于 grid_z 以隔离圆圈内的所有值并计算它们的平均值。

更好的方法是直接在 grid_xgrid_y 上使用掩码,只在需要的点上插入函数。

# Compute the mask of a circle
center_grid_x = 0.5
center_grid_y = 0.5
radius = 0.25
mask = (grid_x - center_grid_x) ** 2 + (grid_y - center_grid_y) ** 2 < radius **2

# The mask can be visualized with 
# plt.imshow(mask)

# Apply the mask to grid_z and compute the mean
mean1 = np.mean(grid_z[mask])

# Or better compute only the values of points inside the circle
values_z = griddata(points,values,(grid_x[mask],grid_y[mask),method='linear')
mean2 = np.mean(values_z)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。