Skip to content

Instantly share code, notes, and snippets.

@mkacky
Created June 22, 2013 10:09
Show Gist options
  • Save mkacky/5840273 to your computer and use it in GitHub Desktop.
Save mkacky/5840273 to your computer and use it in GitHub Desktop.
example of sum()
#! /usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
## 2x4の行列を作成
A = np.arange(8).reshape(2,4)
# >>> A
# array([[0, 1, 2, 3],
# [4, 5, 6, 7]])
## 列方向の和をとり,行ベクトルを出力
row_sum = np.sum(A, axis=0)
# >>> row_sum
# array([ 4, 6, 8, 10])
## 行方向の和をとり,列ベクトルを出力
col_sum = np.sum(A, axis=1)
# >>> col_sum
# array([ 6, 22])
## 要素の総和を取る
A.sum()
>>> A.sum()
28
## col_sumを求めているのと同義の文
B = np.zeros(A.shape[0])
for i in range( A.shape[0] ) :
B[i] = A[i].sum()
# >>> B
# array([ 6., 22.])
## row_sumを求めているのと同義の文
C = np.zeros(A.shape[1])
for i in range( A.shape[1] ) :
C[i] = A[:,i].sum()
# >>> C
# array([ 4., 6., 8., 10.])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment