我试图通过从另一个 NetCDf 文件(“源”文件)获取值来填充 NetCDF 文件(我们称之为“目标”文件)中的 nan 值。 【两个示例文件可以下载from here] 我正在考虑使用以下框架在 python 中执行此操作:
Step1- identifying the nan values in the Target file, and extracting the location (lat/long), storing in a dataframe
Step2- Extracting the corresponding values of the stored lat/long from the Source file
Step3- writing these values into the Target file
我想出了以下代码:
import pandas as pd
import xarray as xr
import numpy as np
Source = xr.open_dataset("Source.nc")
Target = xr.open_dataset("Target.nc")
#Step 1
df = Target.to_dataframe()
df=df.reset_index()
df2=(df.loc[df['ET'].isin([32767,'nan'])])
#Step2
lat = df2["lat"]
lon = df2["lon"]
point_list = zip(lat,lon)
Newdf = pd.DataFrame([])
for i, j in point_list:
dsloc = Source.sel(lat=i,lon=j,method='nearest')
DT=dsloc.to_dataframe()
Newdf=Newdf.append(DT,sort=True)
这存在三个问题: 1-我不知道如何执行第三步
2-第二步需要永远完成,因为可能有很多遗漏的点
3- 这只是一次步骤!使用这两个文件。
所以,我相信在 python 或 cdo/Nco 中可能有更好、更简单、更快的方法...... 欢迎任何想法和解决方案...谢谢... 请注意,两个 NC 文件具有不同的空间分辨率(维度)。
最佳答案
您可以使用Xarray's where
method为了这。如果你关心效率,你真的想远离 python for 循环。以下是其工作原理的示例:
# these are the points you want to keep
# you can fine tune this further (exclude values over a threshold)
condition = target.notnull()
# fill the values where condition is false
target_filled = target.where(condition, source)
关于python - 使用另一个 netcdf 文件填充 netcdf 文件中的 nan 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58924759/