[Python] How to align xarray dimensions without performing calculation?

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I have 2 DataArrays with partially overlapping dimensions. If I perform any calculation the dimensions of the result are auto aligned according to the exact matches between the overlapping dimensions.

    How can I achieve the same result without performing the redundant calculation below:y_da.y * x_da.x/x_da.x?

    I tried: align, broadcast, merge methods without any success...

    import xarray as xr
    import pandas as pd

    x_da = pd.DataFrame({
    'reporting_date': pd.to_datetime([
    '2024-01-01','2024-02-01','2024-03-01',
    '2024-01-01','2024-02-01','2024-03-01',
    '2024-01-01','2024-02-01','2024-03-01',
    ]),
    'user': [
    'A','A','A',
    'B','B','B',
    'C','C','C',
    ],
    'rating': [
    1,1,1,
    1,2,3,
    3,2,1
    ],
    'x': [
    10,20,30,
    20,30,40,
    30,40,50
    ]
    })

    y_da = pd.DataFrame({
    'rating': [
    1,1,1,1,1,1,
    2,2,2,2,2,2,
    3,3,3,3,3,3
    ],
    'horizon': [
    1,2,3,4,5,6,
    1,2,3,4,5,6,
    1,2,3,4,5,6
    ],
    'y': [
    0.1,0.2,0.3,0.4,0.5,0.6,
    0.2,0.3,0.4,0.5,0.6,0.7,
    0.3,0.4,0.5,0.6,0.7,0.8,
    ]
    })

    x_da = x_da.set_index(['user','reporting_date','rating']).to_xarray()
    y_da = y_da.set_index(['rating','horizon']).to_xarray()


    ds = x_da.assign(y=y_da.y * x_da.x/x_da.x)


    display(ds.sel({'user':'A'}).y)


    [​IMG]

    Continue reading...

Compartilhe esta Página