给定一个具有以下结构的数据集:
time var1 var2 var2 var1 var3
loc1 loc1 loc2 loc2 loc1
1 11 12 13 14 15
2 21 22 23 25
3 32 33 34 35
Run Code Online (Sandbox Code Playgroud)
以 .csv 形式给出:
time,var1,var2,var2,var1,var3
,loc1,loc1,loc2,loc2,loc1
1,11,12,13,14,15
2,21,22,23,,25
3,,32,33,34,35
Run Code Online (Sandbox Code Playgroud)
注意:缺少一些值,并非所有变量都适用于所有位置,时间戳适用于每个记录,列可能会出现乱序,但时间戳可靠地是第一列。我不确定所有这些方面都与最佳解决方案相关,但它们确实存在。
我在设置 xarray 三维数组时没有遇到太多麻烦,该数组允许我通过时间戳、位置、变量名称访问值。在确定唯一的位置名称后,它会循环遍历位置名称,按位置过滤数据并一次添加一个位置的结果。但我想知道 pythonic 和 pandastic 解决方案(由于缺乏更好的词)会是什么样子?
问题:是否有一些紧凑且有效的方法(可能使用 pandas 和 xarray)将此数据集或任何类似的数据集(具有不同的变量和位置名称)从 .csv 加载到 3d 数组(如 xarray DataArray)中?
我发现 xarray 执行变量重采样以及平均值和标准差计算的惊人能力。
是否有像 .mean() 方法一样在数据时间重采样后直接计算偏度的方法?
谢谢
对于多维滚动窗口使用 xarray 滚动构造的最佳方法是什么?这是一个 numpy 示例:
import numpy as np
from numpy.lib.stride_tricks import as_strided
data = np.array(np.arange(6).reshape(2, 3),dtype="float64")
win_size = (
3 # Size of the window (e.g. 3*3)
)
win_size_half = int(np.floor(win_size / 2))
# pad with nan to get correct window for the edges
data = np.pad(
data,
(win_size_half, win_size_half),
"constant",
constant_values=(np.nan),
)
sub_shape = (win_size, win_size)
view_shape = tuple(np.subtract(data.shape, sub_shape) + 1) + sub_shape
data_view = as_strided(
data, view_shape, data.strides * 2
)
data_view = data_view.reshape((-1,) + sub_shape) …Run Code Online (Sandbox Code Playgroud) 这是我的代码中函数的内存分析器的输出,使用 xarray (v.0.16.1) 数据集:
Line # Mem usage Increment Line Contents
================================================
139 94.195 MiB 94.195 MiB @profile
140 def getMaps(ncfile):
141 335.914 MiB 241.719 MiB myCMEMSdata = xr.open_dataset(ncfile).resample(time='3H').reduce(np.mean)
142
143 335.945 MiB 0.031 MiB plt.figure(figsize=(20.48, 10.24))
144
145 # projection, lat/lon extents and resolution of polygons to draw
146 # resolutions: c - crude, l - low, i - intermediate, h - high, f - full
147 336.809 MiB 0.863 MiB map = Basemap(projection='merc', llcrnrlon=-10.,
148 335.945 MiB 0.000 …Run Code Online (Sandbox Code Playgroud) 我试图用最接近的值填充二维 xarray (lat, lon) 中的 NaN。
我有以下示例代码,其中应用了陆地-海洋掩模。然后我想用它们各自最接近的陆地点值填充海洋点。
我知道 bfill 和 ffill 会按照这些思路做一些事情,但不完全是我想要的。
理想情况下,所有海洋点应在最后填充。
有任何想法吗?
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import regionmask
def mask_ocean(arr, maskValue=np.nan):
land = regionmask.defined_regions.natural_earth.land_110.mask(arr)
masked = xr.where(land==0, arr, maskValue)
return masked
# Create sample data
lon = np.arange(129.4, 153.75+0.05, 0.25)
lat = np.arange(-43.75, -10.1+0.05, 0.25)
data = 10 * np.random.rand(len(lat), len(lon))
ds = xr.Dataset({"DC": (["lat", "lon"], data)}, coords={"lon": lon,"lat": lat})
#< Mask ocean
ds = mask_ocean(ds) …Run Code Online (Sandbox Code Playgroud) 在xarray中有一个方法叫做to_dataframe(),参见:
http://xarray.pydata.org/en/stable/pandas.html
使用此方法可以将 DataArray 转换为 pandas DataFrame。
如何将 xarray DataArray 转换为 geopandas GeoDataFrame,与上面类似,但网格单元中包含多边形?
我有一个具有多个时间维度的 xarray slow_time,fast_time一个维度代表不同的对象object,一个维度反映每个对象在每个时间点的位置coords。
scipy.spatial.transform.Rotation现在的目标是针对每个时间点对该数组中的每个位置应用旋转。
我正在努力弄清楚如何使用来做我想做的事情,主要是因为我不太清楚xarray.apply_ufunc这个概念。input_core_dimensions
下面的代码显示了我正在尝试做的事情:
import numpy as np
import xarray as xr
from scipy.spatial.transform import Rotation
# dummy initial positions
initial_position = xr.DataArray(np.arange(6).reshape((-1,3)), dims=["object", "coords"])
# dummy velocities
velocity = xr.DataArray(np.array([[1, 0, 0], [0, 0.5, 0]]), dims=["object", "coords"])
slow_time = xr.DataArray(np.linspace(0, 1, 10, endpoint=False), dims=["slow_time"])
fast_time = xr.DataArray(np.linspace(0, 0.1, 100, endpoint=False), dims=["fast_time"])
# times where to evaluate my function
times = slow_time + fast_time
# this is …Run Code Online (Sandbox Code Playgroud) 我有一个数组,我想选择前 2 个或范围,跳过下一个 2,选择下一个 2,然后继续直到列表末尾
list = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
results_wanted = [2,4,9,10,12,2] # note how it skipping 2. 2 is used here as and example
Run Code Online (Sandbox Code Playgroud)
有没有办法在Python中实现这一点?
我想绘制两个时间序列,其中一个在 cftime 中,另一个在 datetime 中。
一种可能性是将cftime 转换为 datetime,但这可能会给非标准 cftime 日历(例如 NoLeap)带来奇怪的结果。因此,我正在尝试将日期时间转换为 cftime。
我可以按如下方式暴力破解它,但是有可用的内置方法吗?
>>> import pandas as pd
>>> import xarray as xr
>>>
>>> da = xr.DataArray(
... [1, 2], coords={"time": pd.to_datetime(["2000-01-01", "2000-02-02"])}, dims=["time"]
... )
>>> print(da.time)
<xarray.DataArray 'time' (time: 2)>
array(['2000-01-01T00:00:00.000000000', '2000-02-02T00:00:00.000000000'],
dtype='datetime64[ns]')
Coordinates:
* time (time) datetime64[ns] 2000-01-01 2000-02-02
>>>
>>>
>>> import cftime
>>>
>>>
>>> def datetime_to_cftime(dates, kwargs={}):
... return [
... cftime.datetime(
... date.dt.year,
... date.dt.month,
... date.dt.day,
... date.dt.hour,
... …Run Code Online (Sandbox Code Playgroud) 我正在使用xarray. 组合多个 netcdf 文件xarray.open_mfdataset。但是我在运行命令时收到错误,下面是命令和错误。
nc_all = xarray.open_mfdataset(files,combine = 'nested', concat_dim="time")
files = glob.glob("/filepath/*")
Run Code Online (Sandbox Code Playgroud)
我收到以下错误 -
Traceback (most recent call last):
File "/home/lsrathore/GLEAM/GLEAM_HPC.py", line 85, in <module>
nc_1980_90 = xarray.open_mfdataset(files[1:11],combine = 'nested', concat_dim="time")
File "/home/lsrathore/.local/lib/python3.9/site-packages/xarray/backends/api.py", line 1038, in open_mfdataset
datasets = [open_(p, **open_kwargs) for p in paths]
File "/home/lsrathore/.local/lib/python3.9/site-packages/xarray/backends/api.py", line 1038, in <listcomp>
datasets = [open_(p, **open_kwargs) for p in paths]
File "/home/lsrathore/.local/lib/python3.9/site-packages/xarray/backends/api.py", line 572, in open_dataset
ds = _dataset_from_backend_dataset(
File "/home/lsrathore/.local/lib/python3.9/site-packages/xarray/backends/api.py", line 367, in _dataset_from_backend_dataset
ds …Run Code Online (Sandbox Code Playgroud) python-xarray ×10
python ×8
numpy ×3
csv ×1
datetime ×1
geopandas ×1
netcdf ×1
netcdf4 ×1
pandas ×1
python-3.x ×1
resampling ×1
scipy ×1
skew ×1