El Confuso
El Confuso

Reputation: 1981

Opening a binary (32 bit signed integer .dat) file into numpy arrays

I have a 32 bit signed integer .dat file with two arrays where the data is interleaved. I want to open the data into two separate numpy arrays.

I have tried to open it using numpy 'fromfile'.

import numpy as np

newarray = np.fromfile('file.dat',dtype=int)
print newarray

From my file, this prints

[ 83886080 16777216 251658240 ..., 0 50331648 16777216]

Which is odd because I know the two arrays should start like

[  1   0   0  ...]
[  15  5   11 ...]

Based on my understanding of the interleaved data I was expecting the above code to give me 1 array which looked something like

[  1   15   0   5 ...]

Does anyone know where I'm going wrong? I can post the file if it would help.

Upvotes: 0

Views: 1583

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114811

Try:

data = np.fromfile('file.dat', dtype=np.int32)
arr1 = data[::2]
arr2 = data[1::2]

or

data = np.memmap('file.dat', dtype=np.int32, mode='r')
arr1 = data[::2]
arr2 = data[1::2]

Upvotes: 1

Related Questions