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?
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.
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.
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.
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]
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With