Home > Blockchain >  Numpy, Reading from File with no delimiter, and most efficient way
Numpy, Reading from File with no delimiter, and most efficient way

Time:10-03

I'm looking for most efficient way to load file with matrix to numpy array without delimiter.

should I use generator to convert and fill? file consist of single 1 and 0 only

000000000
011111111
111000100
110001110
000001100
001000000
110000000
111111100

to:

[
  [0, 0, 0, 0, 0, 0, 0, 0, 0]
  [0, 1, 1, 1, 1, 1, 1, 1, 1]
  [1, 1, 1, 0, 0, 0, 1, 0, 0]
          ...
]

CodePudding user response:

You can use numpy.genfromtxt

import numpy as np

np.genfromtxt('matrix.txt', delimiter=1, dtype=int)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 1, 0, 0],
       [1, 1, 0, 0, 0, 1, 1, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 0, 0]])
  • Related