如何在xarray中为给定维度和坐标添加新值?

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

我的数据具有以下 xarray 数据集表示形式:

df = pd.DataFrame({
    'var': np.random.rand(16),
    'country': 4*['UK'] + 4*['US'] + 4*['FR'] + 4*['DE'],
    'time_delta': 4*list(pd.timedelta_range(
        start='30D',
        periods=4,
        freq='30D'
    )),
})

ds = df.set_index(['country','time_delta']).to_xarray()

我想为给定的新坐标和给定的尺寸添加变量的新值,同时保持现有尺寸:

为维度=time_delta的坐标='0D'设置变量=var的值=0,同时保留其他现有的 尺寸(在这种情况下是国家/地区)。

在 pandas 中我可以通过以下方式做到这一点:

# 1. Pivot long to wide
df_wide = df.pivot(
    index='country',
    columns='time_delta'
).droplevel(0,axis=1)

# 2. Set value
df_wide['0D'] = 0

# 3. Melt wide to long
df_new = df_wide.melt(ignore_index=False).rename(
    columns={'value': 'var'}
).reset_index()

ds_new = df_new.set_index(['country','time_delta']).to_xarray()

有没有在xarray中进行此类操作的通用方法,以便直接实现

ds -> ds_new

python pandas python-xarray
1个回答
0
投票

在Xarray中,您可以使用以下方法获得相同的结果。这是执行您所描述的操作的代码:

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

# Original dataset creation
df = pd.DataFrame({
    'var': np.random.rand(16),
    'country': 4*['UK'] + 4*['US'] + 4*['FR'] + 4*['DE'],
    'time_delta': 4*list(pd.timedelta_range(
        start='30D',
        periods=4,
        freq='30D'
    )),
})

ds = df.set_index(['country', 'time_delta']).to_xarray()

# Adding new value for the given coordinate and dimension
ds_new = ds.copy()  # Make a copy to avoid modifying the original dataset
ds_new['var'].loc[{'time_delta': '0D'}] = 0

# Display the new dataset
print(ds_new)

此代码利用 Xarray 的

.loc
访问器将“time_delta”维度中指定坐标(“0D”)的“var”变量的值设置为 0。此操作修改
ds_new
数据集,同时保持原始
ds
数据集不变。

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