Pandas DF 到 Xarray 数据集

问题描述 投票:0回答:1

嗨,最初我的 Xarray 数据集如下:

<xarray.Dataset>
Dimensions:    (latitude: 721, longitude: 1400, time: 71)
Coordinates:
  * time       (time) datetime64[ns] 2000-12-31 2001-12-31 ... 2018-12-31
  * longitude  (longitude) float32 -22.5 -21.75 -21.0 -20.25 ... 43.5 44.25 45.0
  * latitude   (latitude) float32 72.0 71.25 70.5 69.75 ... 28.5 27.75 27.0
Data variables:
    tas      (time, latitude, longitude) float64 5.033e+05 ... 1.908e+05

现在我将其转换为数据帧,并在

latitude and longitude
上使用 groupby 函数来获取所有时间维度上的
tas
值,这是样本 df ,它将具有
1038239 records(721 * 1440)
,而 tas 将具有
71 values(71 time)
数组:

latitude    longitude   tas
-90.0        358.75     [50603.53125, 50002.609375, 50183.98828125, 49...
-90.0        359.00     [50603.53125, 50002.609375, 50183.98828125, 49...
-90.0        359.25     [50603.53125, 50002.609375, 50183.98828125, 49...
-90.0        359.50     [50603.53125, 50002.609375, 50183.98828125, 49...
-90.0        359.75     [50603.53125, 50002.609375, 50183.98828125, 49...

现在我已经执行了一些操作并创建了新列

tas_new
,其大小与
tas
相似。现在我想创建新的数据集或在具有相同维度的旧数据集中添加此变量
(time, latitude, longitude)
。但我无法将其重塑回旧的样子。

我尝试从

tas_new
获取所有值并将它们像这样堆叠起来:

array_tuple = (df_groups['trend'].values)
arrays = np.vstack(array_tuple)

这确实返回了形状为

(1038239, 71)
的数组。有人可以指导我如何恢复原始形状并将该变量添加到 xarray 数据集或创建新的形状。

预期结果:

<xarray.Dataset>
Dimensions:    (latitude: 721, longitude: 1400, time: 71)
Coordinates:
  * time       (time) datetime64[ns] 2000-12-31 2001-12-31 ... 2018-12-31
  * longitude  (longitude) float32 -22.5 -21.75 -21.0 -20.25 ... 43.5 44.25 45.0
  * latitude   (latitude) float32 72.0 71.25 70.5 69.75 ... 28.5 27.75 27.0
Data variables:
    tas      (time, latitude, longitude) float64 5.033e+05 ... 1.908e+05
    tas_new  (time, latitude, longitude) float64 5.033e+05 ... 1.908e+05

或来自数据帧的维度为

(time, latitude, longitude)
的数组。

python pandas dataframe pandas-groupby python-xarray
1个回答
1
投票

因此,一旦我有了,

arrays = np.vstack(array_tuple)
,我将它们转换为整个列表,形状为
(1038239*71)
,然后添加与其经纬度时间对相对应的原始数据帧。然后将整个数据帧转换回 xarray。

PS:所以数据帧非常大,需要转换成 xarray 以减少内存(<12GB) system, so I broke the dataframe into 7 parts converted each of them into xarray and then concatenated them to get full Xarray dataset.

© www.soinside.com 2019 - 2024. All rights reserved.