xarray多索引con的最佳实践

2024-05-19 13:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组1000(2D)pd.Dataframe(比如说,索引:时间,列:run_id),每个属性都有3个属性(比如温度、压力、位置)。理想情况下,我希望在一个5维的xr.DataArray中包含所有内容(或者具有4个维度的xr.dataset中的所有内容,并将最后一个维度作为唯一的数据变量)。在

我创建了一个带有两个dim和2+3个坐标的DataArray,但是xr.concat似乎不适用于多个维度。(我遵循了这里提到的方法Add 'constant' dimension to xarray Dataset。)在

示例:我从单个数据帧和属性列表构建数据数组。在

# Mock data:
data = {}
for i in np.arange(500):
    data[i] = pd.DataFrame(np.random.randn(1000, 8), index=pd.DatetimeIndex(start='01.01.2013',periods=1000,freq='h'),
                    columns=list('ABCDEFGH'))
df_catalogue = pd.DataFrame(np.random.choice(10,(500, 3)), columns=['temp','pre','zon'])

#Build DataArrays adding scalar coords
res_da = []
for i,v in df_catalogue.iterrows():
    i_df = data[i] # data is a dictionary of properly indexed dataframes

    da = xr.DataArray(i_df.values,
                   coords={'time':i_df.index.values,'runs':i_df.columns.values,
                           'temp':v['temp'], 'pre':v['pre'],'zon':v['zon']},
                   dims=['time','runs'])
    res_da.append(da)

但是当我尝试all_da = xr.concat(res_da, dim=['temp','pre','zon'])时,我得到了奇怪的结果。实现这一目标的最佳方法是:

^{pr2}$

Tags: columns数据dfdata属性nprespre
1条回答
网友
1楼 · 发布于 2024-05-19 13:26:05

xarray.concat仅支持沿单个维度连接。但我们可以通过串联、设置多重索引然后取消堆叠来解决这个问题。在

我改变了你的设置代码,因为这只在你构建的新坐标(['temp','pre','zon'])的每个组合都是唯一的情况下才有效:

import numpy as np
import pandas as pd
import xarray as xr
import itertools

data = {}
for i in np.arange(500):
    data[i] = pd.DataFrame(np.random.randn(1000, 8),
                           index=pd.DatetimeIndex(start='01.01.2013',periods=1000,freq='h'),
                           columns=list('ABCDEFGH'))
cat_data = [(x, y, z)
            for x in range(20)
            for y in ['a', 'b', 'c', 'd', 'e']
            for z in ['A', 'B', 'C', 'D', 'E']]
df_catalogue = pd.DataFrame(cat_data, columns=['temp','pre','zon'])

#Build DataArrays adding scalar coords
res_da = []
for i,v in df_catalogue.iterrows():
    i_df = data[i] # data is a dictionary of properly indexed dataframes

    da = xr.DataArray(i_df.values,
                   coords={'time':i_df.index.values,'runs':i_df.columns.values,
                           'temp':v['temp'], 'pre':v['pre'],'zon':v['zon']},
                   dims=['time','runs'])
    res_da.append(da)

然后,我们可以简单地写下:

^{pr2}$

从而得到您想要的5D阵列:

<xarray.DataArray (time: 1000, runs: 8, temp: 20, pre: 5, zon: 5)>
array([[[[[-0.690557, ..., -1.526415],
          ...,
          [ 0.737887, ...,  1.585335]],

         ...,

         [[ 0.99557 , ...,  0.256517],
          ...,
          [ 0.179632, ..., -1.236502]]],


        ...,


        [[[ 0.234426, ..., -0.149901],
          ...,
          [ 1.492255, ..., -0.380909]],

         ...,

         [[-0.36111 , ..., -0.451571],
          ...,
          [ 0.10457 , ...,  0.722738]]]]])
Coordinates:
  * time     (time) datetime64[ns] 2013-01-01 2013-01-01T01:00:00 ...
  * runs     (runs) object 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H'
  * temp     (temp) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  * pre      (pre) object 'a' 'b' 'c' 'd' 'e'
  * zon      (zon) object 'A' 'B' 'C' 'D' 'E'

相关问题 更多 >