numpy.ndarray と Rのapply()

  • Rの行列で、各行の和を出そうと思ったら
M <- matrix(rnorm(100),10,10)
apply(M,1,sum)
  • だろう
  • 同じことをPythonでやるのはどうするのかな、と思った
  • Pythonで行列を扱うならnumpyがよいのでそうすることにしたとして
  • 値のセットの和を出すsum()関数を、軸方向に指定して計算することもできて
M = np.array(np.random.randint(5,18000,100)).reshape(10,10)
np.sum(M,axis=1)
  • とするらしい。Rのapply(M,1,sum)と同じ構成
  • それとは別に:
  • numpyのndarrayにはuniversal functionsというのがある。名前は「大層」だが、全要素に同じ処理をして、同じサイズのndarrayを作る関数のこと(種類がたくさんある)
  • このuniversal functionを繰り返し使って、答えをたたんでいくという処理をしろ、という指示である、reduceという「高階関数」と組み合わせるらしい
M = np.array(np.random.randint(5,18000,100)).reshape(10,10)
np.add.reduce(M,axis=1)
  • ちなみに、universal functionsのリストはここにある
  • また、recude以外にも、「高階関数的ndarray処理」として、以下のようなものがあるらしい。どういううまみがあるのかまだわからない
    • ufunc.reduce(a[, axis, dtype, out, …])
      • Reduces a’s dimension by one, by applying ufunc along one axis.
    • ufunc.accumulate(array[, axis, dtype, out])
      • Accumulate the result of applying the operator to all elements.
    • ufunc.reduceat(a, indices[, axis, dtype, out])
      • Performs a (local) reduce with specified slices over a single axis.
    • ufunc.outer(A, B, **kwargs)
      • Apply the ufunc op to all pairs (a, b) with a in A and b in B.
    • ufunc.at(a, indices[, b])
      • Performs unbuffered in place operation on operand ‘a’ for elements specified by ‘indices’.
  • reduceのほかに、基本となる「高階関数」についてはこちらなどで。