6
3

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 3 years have passed since last update.

flattenとravel

Posted at

こんにちは。
昨日の記事はイマイチだったのでもっと分解して、理解を深めたいと思います。

今日はflatten関数とravel関数の違いです。
どっちも配列を一元化する為の関数です。
基本的にはflatten関数を使うようですが、ravel関数の方が処理が速い場合もあるようです。
では、それぞれ見ていきましょう。

flattenについて

まず初めtにflattenのAPI

numpy.ndarray.flatten(order = ‘C’)

パラメーターとしてorderを持つが、今回の内容にはあまり関係ないので詳細は伏せます。
もし、気になる人はflattenを見てください。
例文を見て見ましょう。

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
a = np.reshape((2, 5))
b[4] = 251
b = a.flatten()
print('a : ', a)
print('b : ', b)
a :  [[ 1  2  3  4  5]
    [ 6  7  8  9 10]]

b :  [   1    2    3    4 251    6    7    8    9   10]

表示する前にbのindex=5の所に251という素数を入れても、オリジナルの**"a"は変わっていません。**
なぜ素数かって?美しいから。:eyes:

話を戻すと、a.flatten()の所で"a"はコピーされてbに渡されているわけですね。
では、ravelはどうでしょうか?

ravelについて

まず初めにravelのAPI

numpy.ravel(a, order=’C’)
もしくは、
numpy.ndarray.ravel(order=’C’)

まず一つ目の違いとして、ravelの場合は1次元配列にしたい配列をパラメータとして持つことができます。
もう一つ違いがあります。
一旦、以下のコードを見ていきましょう。

サンプルコード

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape((2, 5))
# b = np.ravel(a)とも書ける。
b = a.ravel()
b[4] = 251
print('a : ', a, end='\n\n')
print('b : ', b)
a :  [[  1   2   3   4 251]
      [  6   7   8   9  10]]

b :  [  1   2   3   4 251   6   7   8   9  10]

なんと!!!!
違いが明確になりましたね。
ravelの場合はbにaの参照を渡しているわけですね。

結局違いは?

flatten() : コピーを渡す。
ravel() : 参照を渡す。そして書き方が二つある。

どっちが良いの?

それは時と場合によります。
速い方はravel
けど、1次元配列に変える前のデータも使いたいならflattenという所でしょう。
どっちも知っておくことで、処理が何倍にも早くなるかもしれません。

ありがとうございました!

参考文献

flatten1
flatten2
ravel

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?