<Python, numpy> numpy.ndarrayの繰り返し

numpy.ndarrayの繰り返し方iterating

次のアレイ インスタンスarray instanceがあった時、

In [110]: a
Out[110]:
array([[ 0,  2,  4],
       [ 6,  8, 10]])

In [111]: g.axes
Out[111]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x2b3583026748>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x2b3582fbceb8>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x2b3585ac2908>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x2b35827d2390>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x2b3585b948d0>]], dtype=object)

In [113]: type(a[0][0])
Out[113]: numpy.int64

In [114]: type(g.axes[0][0])
Out[114]: matplotlib.axes._subplots.AxesSubplot

aは、各要素が数字int
g.axesは、各要素がmatplotlibのAxesオブジェクト
(seaborn.Facetをやると、できるよーん。)

繰り返し方法がいくつか。

その1 .flatを使う。

In [115]: for i in a.flat:
   .....:     print(i)
   .....:
0
2
4
6
8
10

その2 np.nditer()を使う。

In [116]: for i in np.nditer(a):
   .....:     print(i)
   .....:
0
2
4
6
8
10

ただし、この場合、g.axesのような各要素がオブジェクトだとエラーがでる。

In [117]: for i in np.nditer(g.axes):
    print(i)
   .....:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-117-9bf15830e5ec> in <module>()
----> 1 for i in np.nditer(g.axes):
      2     print(i)
      3

TypeError: Iterator operand or requested dtype holds references, but the REFS_OK flag was not enabled

回避するには、お呪いflags=['refs_ok']を追加。

In [120]: for i in np.nditer(g.axes, flags=['refs_ok']):
    print(i)
   .....:
Axes(0.0766725,0.808696;0.878793x0.175137)
Axes(0.0766725,0.613226;0.878793x0.175137)
Axes(0.0766725,0.417756;0.878793x0.175137)
Axes(0.0766725,0.222285;0.878793x0.175137)
Axes(0.0766725,0.0268148;0.878793x0.175137)

詳しいことは、マニュアルに。。。

nditer
numpy.nditer — NumPy v1.10 Manual

繰り返しのやり方。
Iterating Over Arrays — NumPy v1.10 Manual

追加。

np.nditerだと、繰り返しででてくる要素がnumpy.ndarray

In [122]: for i in g.axes.flat:
    print(type(i))
   .....:
<class 'matplotlib.axes._subplots.AxesSubplot'>
<class 'matplotlib.axes._subplots.AxesSubplot'>
<class 'matplotlib.axes._subplots.AxesSubplot'>
<class 'matplotlib.axes._subplots.AxesSubplot'>
<class 'matplotlib.axes._subplots.AxesSubplot'>

In [123]: for i in np.nditer(g.axes, flags=['refs_ok']):
   .....:     print(type(i))
   .....:
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>