学习如何使用 xarray 从 Pandas DF 生成 netCDF 文件。遵循几个教程和 SO 问题将“常量”维度添加到 xarray 数据集并将“常量”维度添加到 xarray 数据集,但仍然存在一些问题,因为我无法将 Date_Time、lat 和 lon 作为维度。当我进行 nc 转储时,它们不正确。
将txt文件导入pandas df然后xr到netCDF的初始方法:
import pandas as pd
import xarray
#IMport Data from .dat file
colnames1 = ['Date','Time','latitude','longitude','Status','depth']
df2 = pd.read_csv('test.txt',header=0,error_bad_lines=False, names = colnames1,delim_whitespace=True)
# create xray Dataset from Pandas DataFrame
xr = xarray.Dataset.from_dataframe(df2)
# add variable attribute metadata
xr['latitude'].attrs={'units':'degrees', 'long_name':'Latitude'}
xr['longitude'].attrs={'units':'degrees', 'long_name':'Longitude'}
xr['depth'].attrs={'units':'m', 'long_name':'depth'}
# add global attribute metadata
xr.attrs={'Conventions':'CF-1.6', 'title':'Data', 'summary':'Data generated'}
#print xr
print xr …Run Code Online (Sandbox Code Playgroud) 在函数 apply_ufunc的xarray 文档中,它说:
dask: ‘forbidden’, ‘allowed’ or ‘parallelized’, optional
How to handle applying to objects containing lazy data in the form of dask arrays:
‘forbidden’ (default): raise an error if a dask array is encountered.
‘allowed’: pass dask arrays directly on to func.
‘parallelized’: automatically parallelize func if any of the inputs are a dask array.
If used, the output_dtypes argument must also be provided.
Multiple output arguments are not yet supported.
Run Code Online (Sandbox Code Playgroud)
在Parallel Computing的文档页面中,有一个注释:
对于大多数已经由 dask …
我有 5 个带有系泊电流计数据的 netCDF 文件。每个文件看起来像这样:
<xarray.Dataset>
Dimensions: (BINDEPTH: 50, INSTRDEPTH: 3, LATITUDE: 5, LONGITUDE: 5, TIME: 44106)
Coordinates:
* INSTRDEPTH (INSTRDEPTH) float64 100.0 280.0 600.0
* LATITUDE (LATITUDE) float64 -34.04 -33.8 -33.67 -33.56 -33.51
* LONGITUDE (LONGITUDE) float64 27.57 27.59 27.64 27.72 27.86
* TIME (TIME) datetime64[ns] 2015-04-11T15:00:00 ...
Dimensions without coordinates: BINDEPTH
Data variables:
PRES (TIME, INSTRDEPTH) float32 dask.array<shape=(44106, 3), chunksize=(44106, 3)>
VCUR (TIME, BINDEPTH) float32 dask.array<shape=(44106, 50), chunksize=(44106, 50)>
UCUR (TIME, BINDEPTH) float32 dask.array<shape=(44106, 50), chunksize=(44106, 50)>
WCUR …Run Code Online (Sandbox Code Playgroud) 上下文:我有一个包含 30 年(每日)数据的 netCDF。我想选择特定月份的跨年数据,例如每个 5 月到 3 月期间。
我可以用一个单独的函数进行选择,但我希望有一种直接的方法可以用 xarray 来做到这一点。我安装的版本是0.9.6
python 模块 xarray 极大地支持加载/映射 netCDF 文件,甚至懒惰地使用 dask。
我必须使用的数据源是数以千计的 hdf5 文件,其中包含大量组、数据集、属性——所有这些都是用 h5py 创建的。
问题是:如何将 hdf5 数据(数据集、元数据...)加载(甚至更好地使用 dask、延迟映射)到 xarray 数据集结构中?
有没有人有这方面的经验或遇到过类似的问题?谢谢!
我如何解决这个错误运行我的代码如下。我正在使用下面的函数并在运行窗口中实现循环,但最终得到以下错误。for 循环起作用并挂在某个点上。
def get_grps(s, thresh=-1, Nmin=3):
"""
Nmin : int > 0
Min number of consecutive values below threshold.
"""
m = np.logical_and.reduce([s.shift(-i).le(thresh) for i in range(Nmin)])
if Nmin > 1:
m = pd.Series(m, index=s.index).replace({False: np.NaN}).ffill(limit=Nmin - 1).fillna(False)
else:
m = pd.Series(m, index=s.index)
# Form consecutive groups
gps = m.ne(m.shift(1)).cumsum().where(m)
# Return None if no groups, else the aggregations
if gps.isnull().all():
return 0
else:
agg = s.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
# agg2 = s2.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
return agg, gps
data_spi = …Run Code Online (Sandbox Code Playgroud) 我有一个 3D 维数组。
>>> M2 = np.arange(24).reshape((4, 3, 2))
>>> print(M2)
array([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15],
[16, 17]],
[[18, 19],
[20, 21],
[22, 23]]])
Run Code Online (Sandbox Code Playgroud)
我想计算沿轴 = 0 的特定值的百分位等级。
例如,如果值 = 4,则预期输出为:
[[0.25, 0.25],
[0.25, 0.25],
[0.25, 0.0]]
Run Code Online (Sandbox Code Playgroud)
其中 [0][0] 处的 0.25 是 [0, 6, 12, 18] 等中 4 的百分位等级。
如果值 = 2.5,则预期输出为:
[[0.25, 0.25],
[0.25, 0.0],
[0.0, 0.0]]
Run Code Online (Sandbox Code Playgroud)
我正在考虑使用,scipy.stats.percentileofscore但这个似乎不适用于多维数组。
- - - …
我使用 xarray 在 python 中打开了一个 netcdf 文件,数据集摘要如下所示。
Dimensions: (latitude: 721, longitude: 1440, time: 41)
Coordinates:
* longitude (longitude) float32 0.0 0.25 0.5 0.75 ... 359.25 359.5 359.75
* latitude (latitude) float32 90.0 89.75 89.5 89.25 ... -89.5 -89.75 -90.0
expver int32 1
* time (time) datetime64[ns] 1979-01-01 1980-01-01 ... 2019-01-01
Data variables:
z (time, latitude, longitude) float32 50517.914 ... 49769.473
Attributes:
Conventions: CF-1.6
history: 2020-03-02 12:47:40 GMT by grib_to_netcdf-2.16.0: /opt/ecmw...
Run Code Online (Sandbox Code Playgroud)
我想得到沿纬度和经度维度的 z 值的平均值。
我尝试使用此代码:
df.mean(axis = 0)
但它正在删除时间坐标,并返回给我这样的东西。
Dimensions: (latitude: …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 combine_by_coords 组合两个空间 xarray 数据集。这两个数据集是彼此相邻的两个图块。所以有重叠的坐标。在重叠区域中,其中一个数据集的变量值为 nan。
我使用了带有 compat='no_conflicts' 选项的“combine_by_coords”。但是,它返回沿维度 y错误的单调全局索引。看起来它以前是一个问题,但已修复(此处)。所以我真的不知道为什么我会收到这个错误。这是一个示例(netcdf 磁贴在这里):
import xarray as xr
print(xr.__version__)
>>>0.15.1
ds1=xr.open_dataset('Tile1.nc')
ds2=xr.open_dataset('Tile2.nc')
ds = xr.combine_by_coords([ds1,ds2], compat='no_conflicts')
>>>...
ValueError: Resulting object does not have monotonic global indexes along dimension y
Run Code Online (Sandbox Code Playgroud)
谢谢
我正在一个 Django 项目中工作,我试图从我的数据库中获取所有栅格数据。
这是我在 models.py 中的模型
from django.contrib.gis.db import models
class RasterWithName(models.Model):
raster = models.RasterField()
name = models.TextField()
Run Code Online (Sandbox Code Playgroud)
这是我用来从 django 的 shell 中的数据库中获取所有行的方法。
首先我必须做一个python manage.py shell然后运行下面的代码,一个接一个:
all_objects = RasterWithName.objects.all()
first_object_in_database = all_objects[0]
print(first_object_in_database)
Run Code Online (Sandbox Code Playgroud)
它打印:
RasterWithName object (1)
Run Code Online (Sandbox Code Playgroud)
此外,运行以下行,
print(type(first_object_in_database))
Run Code Online (Sandbox Code Playgroud)
印刷:
<class 'geo.models.RasterWithName'>
Run Code Online (Sandbox Code Playgroud)
然后我运行下面的两行:
raster = first_object_in_database.raster
print(type(raster))
Run Code Online (Sandbox Code Playgroud)
哪个打印:
<class 'django.contrib.gis.gdal.raster.source.GDALRaster'>
Run Code Online (Sandbox Code Playgroud)
如何将此GDALRaster对象转换为更知名的对象,例如gdal Dataset(可以像这样导入:)from osgeo.gdal import Dataset或xarray Dataset(可以像这样导入:)from xarray import Dataset?
############################################### ###
编辑?#1:
############################################### ###
感谢Val,这是一个有效的解决方案:
all_objects …Run Code Online (Sandbox Code Playgroud)