首页 > 解决方案 > 在 Patsy 中创建自定义函数

问题描述

import patsy
from patsy import dmatrices, dmatrix, demo_data
dt=pd.DataFrame({'F1':['a','b','c','d','e','a'],'F2':['X','X','Y','Y','Z','Z']})

我知道我能做到

dmatrix("1+I(F1=='a')",dt)

但是我可以创建一个任意函数吗?我试图在 R 中模仿公式语言中相同级别的灵活性,但在 python 中实现似乎并不直接

def abd(x):
    1 if x in ['a','b','d'] else 0

dmatrix("1+abd(F1)",dt)

标签: pythonpandasformulalazy-evaluationpatsy

解决方案


IIUC

def abd(x):
    return x.isin(['a','b','d'])
dmatrix("1+abd(F1)",dt)
Out[182]: 
DesignMatrix with shape (6, 2)
  Intercept  abd(F1)[T.True]
          1                1
          1                1
          1                0
          1                1
          1                0
          1                1
  Terms:
    'Intercept' (column 0)
    'abd(F1)' (column 1)

推荐阅读