在numpy中获取结果数组的dtype

kiy*_*iyo 5 python numpy scipy

我想为数组操作的输出预分配内存,我需要知道是什么dtype来实现它.下面我有一个功能,可以做我想做的事,但非常难看.

import numpy as np

def array_operation(arr1, arr2):
    out_shape = arr1.shape
    # Get the dtype of the output, these lines are the ones I want to replace.
    index1 = ([0],) * arr1.ndim
    index2 = ([0],) * arr2.ndim
    tmp_arr = arr1[index1] * arr2[index2]
    out_dtype = tmp_arr.dtype
    # All so I can do the following.
    out_arr = np.empty(out_shape, out_dtype)
Run Code Online (Sandbox Code Playgroud)

以上是非常难看的.numpy有没有这样做的功能?

Mik*_*ham 7

你在找numpy.result_type.

(顺便说一句,您是否意识到您可以将所有多维数组作为1d数组访问?您无需访问x[0, 0, 0, 0, 0]- 您可以访问x.flat[0].)