Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the dtype of a result array in numpy

I want to preallocate memory for the output of an array operation, and I need to know what dtype to make it. Below I have a function that does what I want it to do, but is terribly ugly.

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)

The above is pretty ugly. Does numpy have a function that does this?

like image 712
kiyo Avatar asked Sep 02 '11 15:09

kiyo


People also ask

How can you identify the datatype of a given NumPy array?

Creating numpy array by using an array function array(). This function takes argument dtype that allows us to define the expected data type of the array elements: Example 1: Python3.

What is NumPy Dtype (' O ')?

It means: 'O' (Python) objects. Source. The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised.

How do you find Dtype in Python?

To check the data type in pandas DataFrame we can use the “dtype” attribute. The attribute returns a series with the data type of each column. And the column names of the DataFrame are represented as the index of the resultant series object and the corresponding data types are returned as values of the series object.


1 Answers

You are looking for numpy.result_type.

(As an aside, do you realize that you can access all multi-dimensional arrays as 1d arrays? You don't need to access x[0, 0, 0, 0, 0] -- you can access x.flat[0].)

like image 145
Mike Graham Avatar answered Sep 20 '22 18:09

Mike Graham