Turn .txt file into matrix of ints in python

Turn .txt file into matrix of ints in python

Simple way of doing this is:

>>> for row in file:
...     data.append([int(x) for x in row.split()])
...
>>> data
[[4, 2, 45, 21], [0, 92, 12, 2], [345, 9, 3, 4], [1, 2, 39, 93]]

IMO, this is the most pythonic way

for a nested list:

text = 4 2 45 21
0 92 12 2
345 9 3 4
1 2 39 93

[[*map(int, line.split())] for line in text.split(n)]

Out[16]: [[4, 2, 45, 21], [0, 92, 12, 2], [345, 9, 3, 4], [1, 2, 39, 93]]

Turn .txt file into matrix of ints in python

If youre okay with having your data stored as a numpy.ndarray, you can use numpys genfromtext() with the dtype flag set to int:

from StringIO import StringIO
import numpy as np

text = 4 2 45 21
0 92 12 2
345 9 3 4
1 2 39 93

a = np.genfromtxt(StringIO(text), dtype=int)  #replace the arg with your filename

print(a)
#[[  4   2  45  21]
# [  0  92  12   2]
# [345   9   3   4]
# [  1   2  39  93]]

An alternative is to use loadtxt() instead of genfromtxt() as @Zhiya pointed out in the comments.

a = np.loadtxt(StringIO(text), dtype=int)

As per this post, both functions are basically the same except that genfromtxt() provides more options for dealing with missing data.

Leave a Reply

Your email address will not be published. Required fields are marked *