Drkcore

26 12 2013 Python pandas Tweet

逆引きPandas (Matrix編)

R逆引きハンドブックのMatrixの章をPandasで。

ProductName R言語逆引きハンドブック
石田基広
シーアンドアール研究所 / 4830円 ( 2012-01-26 )


Pandasの場合MatrixないからDataFrameだけど。

ProductName Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理
Wes McKinney
オライリージャパン / 3780円 ( 2013-12-26 )


行列ではなくデータフレーム

行列の演算を行う

>>> x = pd.DataFrame([[1,0],[-2,3]])
>>> y = pd.DataFrame([[-1,1],[4,2]])
>>> x.dot(y)
    0  1
0  -1  1
1  14  4
>>> x * y
   0  1
0 -1  0
1 -8  6

x %o% y はわからない

逆行列もnumpyに頼る感じ

行列の次元ごとに演算を適用する

applyでaxisで行か列かを選択する。applyはよく使う

>>> x
   0  1
0  1  0
1 -2  3
>>> x.apply(sum, axis=0) #colsum
0   -1
1    3
dtype: int64
>>> x.apply(sum, axis=1) #rowsum
0    1
1    1
dtype: int64

テータフレームを行列に変換する

numpyのarrayに

>>> x
   0  1
0  1  0
1 -2  3
>>> x.as_matrix()
array([[ 1,  0],
       [-2,  3]], dtype=int64)

行列に行名と列名を設定する

DataFrameなので

>>> x
   0  1
0  1  0
1 -2  3
>>> x.index
Int64Index([0, 1], dtype=int64)
>>> x.columns
Int64Index([0, 1], dtype=int64)
>>> x.index = list("ab")
>>> x.columns = list("cd")
>>> x
   c  d
a  1  0
b -2  3

行列の属性を確認する

>>> x.shape
(2, 2)

行列から成分を抽出する

>>> x
    0   1   2   3
0   1   2   3   4
1   5   6   7   8
2   9  10  11  12
3  13  14  15  16
>>> x.iloc[[2],[3]]
    3
2  12
>>> x.iloc[1:4,[3]]
    3
1   8
2  12
3  16

行列を結合する

rbind

concatで行か列を指定する。これもよく使う

>>> x
   0  1
0  1  0
1 -2  3
>>> x.append(x)
   0  1
0  1  0
1 -2  3
0  1  0
1 -2  3
>>> pd.concat([x, x], axis=0)
   0  1
0  1  0
1 -2  3
0  1  0
1 -2  3

cbind

>>> pd.concat([x, x], axis=1)
   0  1  0  1
0  1  0  1  0
1 -2  3 -2  3

対角行列を作成する

>>> pd.DataFrame(np.diag(range(4)))
   0  1  2  3
0  0  0  0  0
1  0  1  0  0
2  0  0  2  0
3  0  0  0  3

三角行列を作成する

>>> x
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
>>> pd.DataFrame(np.triu(x.as_matrix()))
   0  1  2
0  1  2  3
1  0  5  6
2  0  0  9
>>> pd.DataFrame(np.tril(x.as_matrix()))
   0  1  2
0  1  0  0
1  4  5  0
2  7  8  9

転置行列を作成する

>>> x
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
>>> x.T
   0  1  2
0  1  4  7
1  2  5  8
2  3  6  9

列や行ごとの和や周辺和を求める

>>> x
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
>>> x.sum(axis=0)
0    12
1    15
2    18
dtype: int64
>>> x.sum(axis=1)
0     6
1    15
2    24
dtype: int64
>>> x.sum(axis=0).sum()
45

固有値分解、特異値分解を適用する

固有値分解

>>> x
   0  1
0  4  1
1  1  4
>>> pd.DataFrame(np.linalg.eig(x.as_matrix())[1])
          0         1
0  0.707107 -0.707107
1  0.707107  0.707107

特異値分解は知らん

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021