2017-10-30 6 views
0

行列を表す特定の行を読みたい非常に大きなファイル(〜20 GB)があります。私は文字列のリストを取得する場所現在、私は(hereから)以下のアプローチを使用していますPython:浮動小数点としてファイルから行列を読み取る

2 3 
1 3 
2 2 
1 2 
3 2 
3 4 

:3つの2×2の行列のデータファイルは次のようになります。

しかし、文字列のリストの代わりに浮動小数点を得るにはどうすればよいですか?私はそれを見ませんが、それほど難しくはありません。

答えて

1

拡張ソリューション:

import matplotlib.pyplot as plt, itertools 

n = 2 
num_m = 3 
with open('data', 'r') as f: 
    for i in range(num_m): 
     try: 
      items = [list(map(float, i.split())) for i in itertools.islice(f, n)] 
     except: 
      raise 
     else: 
      plt.matshow(items) 
      plt.show() 

出力:

enter image description here enter image description here enter image description here

2

だけ.splitラインとは、ここではリスト内包表記を使用して、結果にfloat機能をマッピングしていますが、好きなこと:

また
In [29]: from itertools import * 
    ...: n = 2 # matrix size 
    ...: t = 3 # number of matrices 
    ...: with open('data') as f: 
    ...:  for _ in range(t): 
    ...:   s = islice(f, n) 
    ...:   M = [[float(x) for x in line.split()] for line in s] 
    ...:   print(M) 
    ...: 
[[2.0, 3.0], [1.0, 3.0]] 
[[2.0, 2.0], [1.0, 2.0]] 
[[3.0, 2.0], [3.0, 4.0]] 

は注意してください、むしろ、forループを使用する多くのクリーナーですwhileループよりも。

1

numpyののfromfileはここに役立つことができます:

import numpy as np 

n = 2 # matrix size 
t = 3 # number of matrices 

with open('data') as fobj: 
    for _ in range(t): 
     try: 
      numbers = np.fromfile(fobj, count=n * n, sep=' ').reshape(n, n) 
      plt.matshow(numbers) 
      plt.show() 
     except ValueError: 
      break 

は、所望の出力が得られます。

enter image description here enter image description here enter image description here

+0

は、あなたのコード内で行列の数を指定することが可能ですか? – Samuel

+0

それに応じて私の答えを更新しました。 –

関連する問題