【问题标题】:Calculate mean from only one variable in pandas dataframe and netcdf仅从 pandas 数据框和 netcdf 中的一个变量计算平均值
【发布时间】:2022-01-11 21:51:55
【问题描述】:

我的目标是从数据集中计算每日气候学,即通过平均所有年份来获得一年中每一天的海面温度 (SST)(例如,对于 1 月 1 日,所有 1 月 1 日的平均 SST 1982 年至 2018 年)。为此,我做了以下步骤:

数据准备步骤

这是两个数据集的 Drive 链接,以使代码可重现: link to datasets

首先,我加载两个数据集:

ds1 = xr.open_dataset('./anomaly_dss/archive_to2018.nc') #from 1982 to 2018
ds2 = xr.open_dataset('./anomaly_dss/realtime_from2018.nc') #from 2018 to present

然后我转换为 pandas 数据框并将两者合并为一个:

ds1 = ds1.where(ds1.time > np.datetime64('1982-01-01'), drop=True) # Grab all data since 1/1/1982
ds2 = ds2.where(ds2.time > ds1.time.max(), drop=True) # Grab all data since the end of the archive

# Convert to Pandas Dataframe
df1 = ds1.to_dataframe().reset_index().set_index('time')
df2 = ds2.to_dataframe().reset_index().set_index('time')

# Merge these datasets
df = df1.combine_first(df2)

到目前为止,这就是我的数据框的样子:

请注意,LAT,LON 来自 LAT(35,37.7), LON(-10,-5),必须保持这样

异常计算步骤

# Anomaly claculation
def standardize(x):
    return (x - x.mean())/x.std()

# Calculate a daily average
df_daily = df.resample('1D').mean()

# Calculate the anomaly for each yearday
df_daily['anomaly'] = df_daily['analysed_sst'].groupby(df_daily.index.dayofyear).transform(standardize)

我得到以下数据框:

如您所见,我获得了所有三个变量的平均值。

问题

由于我想在地图上绘制气候数据,我不希望将纬度/经度变量平均到一个点。我需要所有纬度/经度点的异常,我真的不知道如何实现。

任何帮助将不胜感激!

【问题讨论】:

    标签: python pandas dataframe netcdf python-xarray


    【解决方案1】:

    我认为您可以通过更简单、更直接的方式完成所有这些操作,而无需将数据数组转换为数据框:

    import os
    
    #Will open and combine automatically the 2 datasets
    DS = xr.open_mfdataset(os.path.join('./anomaly_dss', '*.nc'))
    
    da = DS.analysed_sst
    
    #Resampling
    da = da.resample(time = '1D').mean()
    
    # Anomaly calculation
    def standardize(x):
        return (x - x.mean())/x.std()
    
    da_anomaly = da.groupby(da.time.dt.dayofyear).apply(standardize)
    

    然后您可以绘制任何一天的异常情况:

    da_anomaly[da_anomaly.dayofyear == 1].plot()
    

    【讨论】:

    • 感谢@Thrasy 的回答,但是,我收到以下错误消息:''坐标变量时间在所有数据集上既不是单调增加也不是单调减少''。有什么想法吗?
    • @OlegRuskiy 很难说没有访问您的数据集,您可能需要重新索引。
    • 我在数据准备步骤正下方提供了数据集的驱动链接:)
    • 好的。我不知道你为什么会得到这个异常,但这里至少有两个问题:1/两个 netCDF 都使用不同的日历(第一个文件使用的日历不是标准的),2/两个文件使用的空间网格是不同的。在将这两个文件合并为数据数组或数据框之前,您必须重新索引它们,以使它们的坐标系保持一致。无论如何,这远远超出了您最初问题的范围。
    • 哦,好吧,我没有注意到日历和网格问题,我会先解决这个问题。谢谢@Thrasy !!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2020-05-22
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多