I have a stream of incoming data that has interleaved real and imaginary integers. Converting these to complex64 values is the slowest operation in my program. This is my current approach:
import numpy as np
a = np.zeros(1000000, dtype=np.int16)
b = np.complex64(a[::2]) + np.complex64(1j) * np.complex64(a[1::2])
Can I do better without making a C extension or using something like cython? If I can't do better, what's my easiest approach using a technology like one of these?
In order to change the dtype of the given array object, we will use numpy. astype() function. The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.
Practical Data Science using Python We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array. We can check the type of numpy array using the dtype class.
The astype() function creates a copy of the array, and allows you to specify the data type as a parameter. The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or you can use the data type directly like float for float and int for integer.
[~]
|1> import numpy as np
[~]
|2> a = np.zeros(1000000, dtype=np.int16)
[~]
|3> b = a.astype(np.float32).view(np.complex64)
[~]
|4> b.shape
(500000,)
[~]
|5> b.dtype
dtype('complex64')
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