我有几个逗号分隔的数据文件,我想将它们加载到 xarray 数据集中。每个文件中的每一行代表固定网格中字段的不同空间值,每个文件代表不同的时间点。网格间距是固定的,不随时间变化。网格的间距不均匀。最终目标是计算max_{x, y} { std_t[ value(x, y, t) * sqrt(y **2 + x ** 2)] }
,其中 sqrt 是平方根,std_t
是相对于时间的标准偏差max_{x, y}
是所有空间中的最大值。
我在加载数据时遇到问题。我不清楚如何将多个 CSV 文件加载到 xarray 数据集中。有一个open_mfdataset
函数,旨在将多个数据文件加载到数据集中,但似乎需要 hdf5 或 netcdf 文件。
似乎无法将常规 CSV 文件加载到 xarray 数据集中,并且需要对数据进行预处理。在我的示例中,我决定预先将 csv 文件预处理为 hdf5 文件,以利用h5netcdf
引擎。这对我来说似乎是 hdf5 特有的问题。
以下是迄今为止我加载数据的最佳尝试。不幸的是,它会产生一个空的 xarray 数据集。我尝试了几个选项open_mfdataset
函数,以下代码只是多次尝试使用该函数的一种实现。
如何将这些 csv 文件加载到单个 xarray 数据集中,以便找到感兴趣值的时间标准差的最大空间跨度?
import xarray as xr
import numpy as np
import pandas as pd
'''
Create example files
- Each file contains a spatial-dependent value, f(x, y)
- Each file represents a different point in time, f(x, y, t)
'''
for ii in range(7):
# create csv file
fl = open('exampleFile%i.dat' % ii, 'w')
fl.write('time x1 x2 value\n')
for xx in range(10):
for yy in range(10):
fl.write('%i %i %i %i\n' %
(ii, xx, yy, (xx - yy) * np.exp(ii)))
fl.close()
# convert csv to hdf5
dat = pd.read_csv('exampleFile%i.dat' % ii)
dat.to_hdf('exampleFile%i.hdf5' % ii, 'data', mode='w')
'''
Read all files into xarray dataframe
(the ultimate goal is to find the
maximum across time of
the standard deviation across space
of the "value" column)
'''
result = xr.open_mfdataset('exampleFile*.hdf5', engine='h5netcdf', combine='nested')
...当我运行代码时,result
变量似乎不包含所需的数据:
In: result
Out:
<xarray.Dataset>
Dimensions: ()
Data variables:
*empty*
Attributes:
PYTABLES_FORMAT_VERSION: 2.1
TITLE: Empty(dtype=dtype('S1'))
VERSION: 1.0
Edit
发布的答案假设空间网格均匀分布。这是一个稍微修改过的示例,它不假设空间点的均匀间隔网格。
该示例还假设三个空间维度。这更符合我的实际问题,我意识到这可能是这个简单示例中的一个重要细节。
import xarray as xr
import numpy as np
import pandas as pd
'''
Create example files
- Each file contains a spatial-dependent value, f(x, y)
- Each file represents a different point in time, f(x, y, t)
'''
for ii in range(7):
# create csv file
fl = open('exampleFile%i.dat' % ii, 'w')
fl.write('time x y z value\n')
for xx in range(10):
for yy in range(int(10 + xx // 2)):
for zz in range(int(10 + xx //3 + yy // 3)):
fl.write('%i %f %f %f %f\n' %
(ii, xx * np.exp(- 1 * yy * zz) , yy * np.exp(xx - zz), zz * np.exp(xx * yy), (xx - yy) * np.exp(ii)))
fl.close()
# convert csv to hdf5
dat = pd.read_csv('exampleFile%i.dat' % ii)
dat.to_hdf('exampleFile%i.hdf5' % ii, 'data', mode='w')
'''
Read all files into xarray dataframe
(the ultimate goal is to find the
maximum across time of
the standard deviation across space
of the "value" column)
'''
result = xr.open_mfdataset('exampleFile*.hdf5', engine='h5netcdf', combine='nested')