简体   繁体   English

沿维度 xarray 相乘/乘积

[英]Multiply/product along a dimension xarray

I was looking for a very easy and elegant way to multiply two DataArrays, that may have different dimensions, along a single axis.我一直在寻找一种非常简单而优雅的方法来沿单个轴相乘两个可能具有不同维度的 DataArray。

My specific case: a first DataArray A has dimensions (lat, lon, natpft) and the second B (lat, natpft) .我的具体情况:第一个 DataArray A具有维度(lat, lon, natpft)和第二个B (lat, natpft) My purpose is to have the product of A data in (lat, lon) multiplied by B values along lat for each natpft .我的目的是让(lat, lon)中的A数据乘以每个natpft沿latB值。 If this operation could also include the nearest option in choosing which latitude to match, it would be great.如果此操作还可以包括选择要匹配的纬度的nearest选项,那就太好了。

I have some ideas in mind but I guess there could be a single line code that can do this task.我有一些想法,但我想可能有一个单行代码可以完成这项任务。 I also hope this could help someone else, since I couldn't find any question about this topic.我也希望这可以帮助其他人,因为我找不到关于这个话题的任何问题。

Not really a one line solution here, but I think it solves your problem?这里不是真正的单线解决方案,但我认为它可以解决您的问题?

First construct some data according to your description (I would suggest you to do this in your post next time).首先根据你的描述构建一些数据(我建议你下次在你的帖子中这样做)。

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

# construct "natpft_1"
natpft_1 = np.random.randn(2, 3)

# create coords
longitude_1 = [1,2]
latitude_1 = [1,2,3]

# put data into a dataset
ds1 = xr.Dataset(data_vars=dict(natpft_1=(["x", "y"], natpft_1)),
                 coords=dict(lon=(["x"], longitude_1),
                             lat=(["y"], latitude_1)),
                 attrs=dict(description="natpft_1"))

# construct "natpft_2" along some dummy latitudes
natpft_2 = np.random.randn(1, 5)[0]

latitude_2 = [0.9,2.2,3.3,4.5,5.3]

# put data into a dataset
ds2 = xr.Dataset(data_vars=dict(natpft_2=(["y"], natpft_2)),
                 coords=dict(lat=(["y"], latitude_2)),
                 attrs=dict(description="natpft_2"))

Then solve your problem:然后解决你的问题:

ds3 = ds1.copy()

for i in range(len(ds3['lon'])):
    for j in range(len(ds3['lat'])):
        nearest_lat_ds2_index = np.argmin(ds2['lat'].values-ds3['lat'].values[j])
        ds3['natpft_1'][i,j] = ds3['natpft_1'][i,j]*ds2['natpft_2'][nearest_lat_ds2_index]


# check results
print(ds3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM