我需要执行类似于此处提供的 Spearman 相关性(针对 Pearson 相关性),我可以在网格数据和气候指数(或自定义时间序列)之间进行关联。
时间序列是一个txt文件,网格数据是一个NetCDF文件。我尝试使用 CDO(但似乎它不允许这种相关性)和 R(使用 cor.test()),但由于这两个数据的大小不同(时间序列的 44 个值和数千个值)每个网格的值),不起作用......
然后我在 ChatGPT 的帮助下尝试使用 Python(使用 scipy),显然它有效,但我不确定它生成的内容是否正确,因为我对 Python 的了解很基础。所以我需要一些帮助来了解代码逻辑是否适合我需要它做的事情......
我的代码如下:
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
# Step 1: Read the time series data
time_series = np.loadtxt("september.txt")
# Step 2: Read the gridded mean sea level pressure data
mslp_data = xr.open_dataset("area.nc")
# Step 3: Calculate Spearman correlation coefficient and p-value
correlation_map = np.zeros_like(mslp_data['msl'][0])
p_value_map = np.zeros_like(mslp_data['msl'][0])
for i in range(mslp_data.sizes['latitude']):
for j in range(mslp_data.sizes['longitude']):
grid_point = mslp_data['msl'][:, i, j]
rho, p_value = spearmanr(time_series, grid_point)
correlation_map[i, j] = rho
p_value_map[i, j] = p_value
# Step 4: Apply significance threshold (p < 0.1)
significant_correlation_map = correlation_map.copy()
significant_correlation_map[p_value_map >= 0.1] = np.nan
# Step 5: Plot the significant correlation coefficients on a map
plt.figure(figsize=(10, 5))
plt.imshow(significant_correlation_map, cmap='coolwarm', origin='lower')
plt.colorbar(label='Spearman Correlation Coefficient')
plt.title('Temporal Correlation with Mean Sea Level Pressure (Significant at 90%)')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()
<0.1) Based on your requirements. Overall your code seems good and with these tweaks it should provide an output.