【问题标题】:convert csv file to nc(netcdf) file using xarray使用 xarray 将 csv 文件转换为 nc(netcdf) 文件
【发布时间】:2021-06-21 23:17:55
【问题描述】:

我想将存储日期、温度值、纬度和经度信息的 CSV 文件转换为具有三个维度的 NetCDF 文件格式。

我的数据框是这样的:

当我在下面使用这个脚本时,它只包含 1 个维度。

    import pandas as pd
    import xarray as xr
    df = pd.read_csv(csv_file)
    xr = df.to_xarray()
    nc=xr.to_netcdf('my_netcdf.nc')

你能帮我解决这个问题吗? 谢谢。

【问题讨论】:

    标签: numpy netcdf python-xarray netcdf4


    【解决方案1】:

    您需要先将时间等设置为 pandas 中的索引。所以修改你的代码是这样的:

    import pandas as pd
    import xarray as xr
    df = pd.read_csv(csv_file)
    df = df.set_index(["time", "lon", "lat"]
    xr = df.to_xarray()
    nc=xr.to_netcdf('my_netcdf.nc')
    

    【讨论】:

    • 很遗憾,脚本存在问题。我的数据在同一日期具有不同的位置和信息。例如,2001 年 5 月 1 日的一行数据:15 lat 15,long 25。另一行 2001 年 5 月 1 日的数据:20 lat:20 long:5。此代码在不同位置记录相同的日期。我想合并日期。
    • 脚本没有问题。您没有在原始问题中说明其他问题。我的脚本解决了您的问题。如果您还有其他问题,请修改问题
    猜你喜欢
    • 2022-07-29
    • 1970-01-01
    • 2021-10-29
    • 2018-05-10
    • 2017-11-05
    • 2015-05-19
    • 2019-02-02
    • 2021-01-22
    • 2018-12-24
    相关资源
    最近更新 更多