johnhenry
johnhenry

Reputation: 1343

Reading 2D matrix from file

I have produced a txt file with the entries of my 2d matrix, of dimension N x N, ordered in the following way:

row column
1    1
1    2
1    3
.
.
.
1    N
2    1
2    2
.
.
.
2    N
.
.
.
N    1
N    2 
.
.
.
N    N

where the numbers represent the indices of the row (left) and column (right), from 1 to N.

I would like to read this with Python, so that I can store my matrix as a list of list, something like what you get from using np.loadtxt which, however, I cannot easily use here (or at least I do not see how)

EDIT:

A simplified version of my file txt, with row, column, value, for N=5 (starting to count from 0)

0 0 0.3
0 1 0.4
0 2 0.2
0 3 0.3
0 4 0.7
1 0 9.3
1 1 3.5
1 2 2.4
1 3 3.1
1 4 3.4
2 0 2.3
2 1 4.5
2 2 7.8
2 3 9.2
2 4 8.1
3 0 7.2
3 1 3.2
3 2 8.2 
3 3 7.2 
3 4 7,4
4 0 0.2
4 1 8.2
4 2 9.2
4 3 0.2 
4 4 0.2 

Upvotes: 0

Views: 138

Answers (2)

johnhenry
johnhenry

Reputation: 1343

I think the best way is to use np.reshape:

import numpy as np
a = np.loadtxt('file.txt')
third_column = a[:, 2]

new_matrix = third_column.reshape((dimension_x, dimension_y))

where dimension_x and dimension_y should be known.

Upvotes: 0

Harvey
Harvey

Reputation: 5821

A brute force method:

table = []
row_values = []
last_row = ''
for line in f:
    row, col, value = line.split()
    if row != last_row:
        last_row = row
        row_values = []
        table.append(row_values)
    row_values.append(float(value))

a slightly more clever method that gets all values and then chops them up into rows:

row_numbers, column_numbers, values = zip(*(line.split() for line in f))
rows = int(max(row_numbers)) + 1
columns = int(max(column_numbers)) + 1
values = [float(v) for v in values]
data = [values[n:] for n in range(0, len(values), columns)]
assert len(data) == rows

Upvotes: 1

Related Questions