LoginSignup
2
1

More than 5 years have passed since last update.

Numpy > TypeError: iteration over a 0-d array > 要素が1つの時にndimが0になる場合がある > 対処

Posted at
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 16.04 LTS desktop amd64
TensorFlow v1.2.1
cuDNN v5.1 for Linux
CUDA v8.0
Python 3.5.2
IPython 6.0.0 -- An enhanced Interactive Python.
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
scipy v0.19.1
geopandas v0.3.0
MATLAB R2017b (Home Edition)

Error

test_0-d_array_171203.py
import numpy as np


ain = 1
wrk = np.log(1) / np.log(2)
xs = np.array(wrk)
print(xs.ndim)

for elem in xs:
    print(elem)

run
$ python3 test_0-d_array_171203.py 
0
Traceback (most recent call last):
  File "test_0-d_array_171203.py", line 9, in <module>
    for elem in xs:
TypeError: iteration over a 0-d array

log同士の除算などの場合でndimが0になる場合があるようだ。

対処

以下で対処する。

test_0-d_array_171203.py
import numpy as np


ain = 1
wrk = np.log(1) / np.log(2)
xs = np.array(wrk)
print(xs.ndim)

if xs.ndim == 0:
    xs = [xs]

for elem in xs:
    print(elem)
run
$ python3 test_0-d_array_171203.py 
0
0.0
2
1
0

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
2
1