Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to convert an interleaved NumPy integer array to complex64?

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?

like image 664
Jim Hunziker Avatar asked Apr 14 '11 02:04

Jim Hunziker


People also ask

How do I change the Dtype of a NumPy array?

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.

What is Astype NumPy?

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.

What is the use of an array's Astype method in Python?

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 Answers

[~]
|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')
like image 134
Robert Kern Avatar answered Sep 28 '22 18:09

Robert Kern