LoginSignup
6
7

More than 5 years have passed since last update.

patsyを使ってPythonでもformulaを使う

Posted at

Rの場合

Rにはformulaオブジェクトというものがあり、特徴ベクトルの変換(dummy coding, 交互作用項の追加など)において非常に便利である。

# データフレームの生成
> df <- data.frame(x=c('a', 'b', 'c'), y=c(1, 2, 3))
> df
  x y
1 a 1
2 b 2
3 c 3
# model.matrixを使うとカテゴリ変数はdummy codingされる
> m <- model.matrix(as.formula(~0+x+y), data=df)
> m
  xa xb xc y
1  1  0  0 1
2  0  1  0 2
3  0  0  1 3
attr(,"assign")
[1] 1 1 1 2
attr(,"contrasts")
attr(,"contrasts")$x
[1] "contr.treatment"

# 交互作用項も追加できる
> m <- model.matrix(as.formula(~0+x+y+x*y), data=df)
> m
  xa xb xc y xb:y xc:y
1  1  0  0 1    0    0
2  0  1  0 2    2    0
3  0  0  1 3    0    3
attr(,"assign")
[1] 1 1 1 2 3 3
attr(,"contrasts")
attr(,"contrasts")$x
[1] "contr.treatment"

Pythonの場合

Pythonでもpatsyというライブラリを使うことでformulaを使用できる。

statsmodels内で使用されているのでstatsmodelsをpip installすると自動的に入る。

$ pip install statsmodels

もちろんpatsy単体でpip installしてもよい。

$ pip install patsy
>>> from patsy import dmatrix
>>> import pandas as pd
>>> df = pd.DataFrame({'x': ['a','b','c'],'y':[1,2,3]})
>>> df
   x  y
0  a  1
1  b  2
2  c  3
# カテゴリ変数はdummy codingされる
>>> m = dmatrix('~0+x+y', data=df)
>>> m
DesignMatrix with shape (3, 4)
x[a]  x[b]  x[c]  y
   1     0     0  1
   0     1     0  2
   0     0     1  3
Terms:
'x' (columns 0:3), 'y' (column 3)
# 交互作用項も追加できる
>>> m = dmatrix('~0+x+y+x*y', data=df)
>>> m
DesignMatrix with shape (3, 6)
x[a]  x[b]  x[c]  y  x[T.b]:y  x[T.c]:y
   1     0     0  1         0         0
   0     1     0  2         2         0
   0     0     1  3         0         3
Terms:
'x' (columns 0:3), 'y' (column 3), 'x:y' (columns 4:6)

参考

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