要素が1つしかない配列をfor文に渡すとエラーがでる
2014年4月22日 コメントを残す
【困ったこと】
numpy.loadtxt()で要素が一つしかない配列を読み込んだとき、その配列をfor文に渡すと、以下のエラーが出る。
TypeError: iteration over a 0-d array
例えば、以下のような一要素の配列がファイルに格納されているケースを考える。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 |
このファイルをnumpy.loadtxt()で読み込んだ場合、0-d arrayとしてnumpy.ndarrayオブジェクトが生成されることがある。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# -*- coding: utf-8 -*- | |
import numpy as np | |
## 1要素の配列をテキストファイルから読み込み | |
a = np.loadtxt("one_element.txt") | |
# 表示例 | |
# >>> a | |
# array(10.0) | |
## 配列の次元数を表示 | |
print "配列の次元数 :", | |
print a.ndim | |
# 実行例 | |
# 配列の次元数 : 0 | |
## forループに配列を渡す。 | |
for i in a: | |
print i | |
# 実行例 | |
# Traceback (most recent call last): | |
# File "./one_element_reader.py", line 21, in <module> | |
# for i in a: | |
# TypeError: iteration over a 0-d array |
中盤のndimからわかるように、0次元配列である。
【対策】
読み込むファイルが要素1つになり得る場合は、numpy.loadtxt()のndminオプションを利用する。
最低次元数を1にすることで、上記のエラーを回避できる。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# -*- coding: utf-8 -*- | |
import numpy as np | |
## 1要素の配列をテキストファイルから読み込み | |
a = np.loadtxt("one_element.txt", ndmin=1) | |
# 表示例 | |
# >>> a | |
# array([ 10.]) | |
## 配列の次元数を表示 | |
print "配列の次元数 :", | |
print a.ndim | |
# 実行例 | |
# 配列の次元数 : 1 | |
## forループに配列を渡す。 | |
for i in a: | |
print i | |
# 実行例 | |
# 10.0 |