python - 在 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)
解决方案
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)
推荐阅读
- postgresql - Debezium Postgres 连接器在不需要时生成新的模式版本
- python-3.x - 如何将列分成组并在组之间循环
- oracle - 如何在客户端 PC 上运行 Oracle APEX 应用程序
- powerbi - DAX 问题,当我在 RETURN 子句中使用 IF 时,过滤器/关系被忽略
- amazon-web-services - 如何在 Hibernate 中以编程方式提供对 ColumnTransofrmer 的读写?
- django - 第 8 行:“空”。您是否忘记注册或加载此标签?
- java - 哪个 PlatformTransactionManager 在 Spring 中用于处理 @Transactional
- integer-overflow - 左移计数 >= 类型的宽度 [-Wshift-count-overflow]
- angular - 允许直接访问路由中定义的 Angular 应用程序 url(浏览器导航)
- java - 在其他几条消息完成后发送消息而不使用外部存储?