ndarray上的numpy除法

时间:2019-04-04 15:01:23

标签: python numpy multidimensional-array

我想创建一个包含另一个ndarray比率的新数组。

第一个简单示例:

import numpy as np
week = np.full((3, 4), 2, dtype=float)
week[:,2] = 0
week[2,0:2] =0
week[0,3] =0.99
week[1,3] =1.99
week[2,3] =0.89

week

返回

array([[2.  , 2.  , 0.  , 0.99],
       [2.  , 2.  , 0.  , 1.99],
       [0.  , 0.  , 0.  , 0.89]])

现在我要计算一个包含周比率的ndarray [:,3]

ratio =  week[:,3].reshape(1,-1).T/ week[:,3]

返回

array([[1.   , 0.497, 1.112],
       [2.01 , 1.   , 2.236],
       [0.899, 0.447, 1.   ]])

正是我想要的。

更一般的情况 前4个维度可以更改的5d数组

weeks_5d= np.full((1,1,2, 3, 4), 2, dtype=float)
weeks_5d[:,:,:,:,2] = 0
weeks_5d[:,:,0,2,0:2] =0
weeks_5d[:,:,1,1,0:2] =0
weeks_5d[:,:,:,0,3] = 0.99
weeks_5d[:,:,:,1,3] = 1.99
weeks_5d[:,:,:,2,3] = 0.89

weeks_5d

返回

array([[[[[2.  , 2.  , 0.  , 0.99],
          [2.  , 2.  , 0.  , 1.99],
          [0.  , 0.  , 0.  , 0.89]],

         [[2.  , 2.  , 0.  , 0.99],
          [0.  , 0.  , 0.  , 1.99],
          [2.  , 2.  , 0.  , 0.89]]]]])

现在我想为每个ndarray计算相同的比率

转置5darray会返回奇怪的结果。

我需要的是

   array([[[[[1.   , 0.497, 1.112],
              [2.01 , 1.   , 2.236],
              [0.899, 0.447, 1.   ]]],

             [[1.   , 0.497, 1.112],
              [2.01 , 1.   , 2.236],
              [0.899, 0.447, 1.   ]]]]])

1 个答案:

答案 0 :(得分:1)

我认为循环是您的最大希望,并且有一种缓慢而快速的方法:

缓慢的方式:

#define MY_MACRO(isTrue) ((isTrue) ? do() : (void)0)

打印

static conditional_do(bool isTrue) { if (isTrue) { do(); } }

显然在python中遍历数组很慢,但这就是发明def get_ratios(arr): ni, nj, nk = arr.shape[:3] last_dim = arr.shape[3] new_arr = np.zeros(shape=(ni, nj, nk, last_dim, last_dim), dtype=np.float64) for i in range(ni): for j in range(nj): for k in range(nk): week = arr[i, j, k] ratio = week[:, 3].reshape(-1, 1) / week[:, 3] new_arr[i, j, k] = ratio return new_arr get_ratios(weeks_5d) 的目的:

最快的方式

array([[[[[1.        , 0.49748744, 1.11235955],
          [2.01010101, 1.        , 2.23595506],
          [0.8989899 , 0.44723618, 1.        ]],

         [[1.        , 0.49748744, 1.11235955],
          [2.01010101, 1.        , 2.23595506],
          [0.8989899 , 0.44723618, 1.        ]]]]])

打印

numba