1

How can I predict the datatype of the resulting array after combining two arrays of certain datatypes, without actually performing the calculation? E.g.

import numpy as np
arr1 = np.array([0.5, 0.1, 1.3, 1.5]).astype(np.float32)
arr2 = np.array([1, 2, 3, 4, 5]).astype(np.uint8)
arr3 = np.array([-10, 2, 3, 4, 120]).astype(np.int8)

output_dtype1 = np.multiply(arr1, arr2).dtype  # np.float32

output_dtype2 = np.multiply(arr2, arr3).dtype  # np.int16

Would it be possible to write a function that returns output_dtype1 and output_dtype2, using arr1.dtype, arr2.dtype, arr3.dtype and the array operator (multiply, add, subtract etc) as arguments ?

4
  • If the arrays aren't too large the actual calculation is probably fastest. ufunc do have signature information, but using that with python level calls is probably slower. Commented Mar 17, 2021 at 18:18
  • Study numpy.org/doc/stable/reference/ufuncs.html#casting-rules Commented Mar 17, 2021 at 20:00
  • My arrays are not necessarily large. My use-case is writing geospatial rasters to file using rasterio, for which the output profile has to be compiled beforehand. Commented Mar 18, 2021 at 8:35
  • For future reference, I've also found the rasterio dtype module, especially the get_minimum_dtype function. Commented Mar 18, 2021 at 10:03

1 Answer 1

1

Based on reading https://numpy.org/doc/stable/reference/ufuncs.html#casting-rules

I tried:

In [196]: np.result_type(np.float32, np.uint8)
Out[196]: dtype('float32')
In [197]: np.result_type(np.int8, np.uint8)
Out[197]: dtype('int16')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.