Interleaving and De-interleaving Data with Python

While working with sound data I had the need to interleave and de-interleave arrays of data.  I also needed it to be very fast. The python package numpy is a very fast, C implementation of multidimensional arrays and provided the base I needed to perform the operations very quickly.

Interleaved Data

Data in a WAV file is stored interleaved, meaning the channels of data are mixed together in frames, where one frame contains one element from each channel.  The diagram below shows interleaved data.

Interleaved data
Interleaved data. Each frame has one element from each channel.

De-interleaved Data

Often when modifying the data, I want to work on only one channel at a time so it is useful to de-interleave the data.  De-interleaved data is stored in individual arrays, one for each channel, rather than in a single array.  The diagram below shows the same data de-interleaved.

De-interleaved data
De-interleaved data. The data is stored in separate arrays, one for each channel.

The Code

I needed fast code to be able to combine or separate the channel data as appropriate.  The numpy library provided the functions I needed.

To interleave data:

To de-interleave data:

 

 

Interleaving and De-interleaving Data with Python