8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python Dictionaryから 2D numpy array の変換方法

Posted at

Dictionaryから2D arrayに変換する必要があったのでその方法のメモ

import numpy as np

myDict = {0: {0: 0, 1: 548, 2: 776, 3: 696, 4: 582},
          1: {0: 548, 1: 0, 2: 684, 3: 308, 4: 194},
          2: {0: 776, 1: 684, 2: 0, 3: 992, 4: 878},
          3: {0: 696, 1: 308, 2: 992, 3: 0, 4: 114},
          4: {0: 582, 1: 194, 2: 878, 3: 114, 4: 0}}

orderedNames = list(myDict.keys())
dataMatrix = np.array([list(myDict[i].values()) for i in orderedNames])
print(dataMatrix)

[[  0 548 776 696 582]
 [548   0 684 308 194]
 [776 684   0 992 878]
 [696 308 992   0 114]
 [582 194 878 114   0]]

ちなみに逆方向は、以下のコードでできます。
参照:https://stackoverflow.com/questions/42949309/convert-2d-numpy-ndarray-to-nested-dictionary

dict = {index:{i:j for i,j in enumerate(k) if j} for index,k in enumerate(array2D)}
print(dict)

たまに変換することがあるので、参照用メモ。

8
6
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?