麻痹的倒数 [英] Reciprocals in patsy
问题描述
Patsy的幂不允许负整数,因此,如果我们有一些序列数据X
,
Patsy's power doesn't allow for negative integers, so, if we have some series data X
,
patsy.dmatrices('X + X**(-1)', X)
返回错误.我该如何将X的倒数添加到这样的小数公式中?
returns an error. How would I add the reciprocal of X to such a patsy formula?
推荐答案
在嵌入式函数调用中关闭了运算符的特殊含义;因此,如果您编写X + 1 / x
,则patsy会将其解释为特殊的patsy +
和/
运算符,但是如果您编写类似X + sin(1 / X)
的内容,则patsy会继续将+
解释为特殊的patsy运算符,但是整个sin(1 / X)
表达式将传递给Python进行评估,Python会将/
评估为常规除法.
The special patsy meaning of operators gets switched off inside embedded function calls; so if you write X + 1 / x
then patsy interprets that as the special patsy +
and /
operators, but if you write something like X + sin(1 / X)
, then patsy continues to interpret the +
as a special patsy operator, but the whole sin(1 / X)
expression gets passed to Python to evaluate, and Python will evaluate the /
as regular division.
因此,如果我们要计算sin(1 / X)
,那就很好.但是我们不(为什么?).我们只想要普通的1 / X
.那我们该怎么办呢?
So that's fine if we wanted to compute sin(1 / X)
. But we don't (why would we?). We just want plain 1 / X
. So how can we do that?
好吧,我们可能会很棘手:我们需要一个函数调用来欺骗patsy的解析器以忽略/
并将其提供给Python-但没有任何东西表明该函数必须要做 .我们可以定义一个识别函数:
Well, we can be tricky: we need a function call to trick patsy's parser into ignoring the /
and giving it to Python -- but there's nothing that says that function has to do anything. We could just define an identify function:
def identity(value):
return value
,然后在类似X + identity(1 / X)
的公式中使用它.
and then use that in a formula like X + identity(1 / X)
.
实际上,这个技巧非常方便,patsy已经为您预定义了一个功能,并将其作为
And in fact, this trick is so handy that patsy has already predefined an function for you, and provides it as a built-in called I(...)
. Generally, you can think of I(...)
as a kind of quoting operator -- it's a way to say "hey patsy, please do not try to interpret anything in this region, just pass it through to Python kthx".
因此,请回答您的原始问题:尝试编写dmatrix("X + I(1 / X)", data)
So to answer your original question: try writing dmatrix("X + I(1 / X)", data)
(下一个问题:为什么使用功能I
和所有这些奇怪的技巧?答案是,这就是30年前R的工作方式,我想不到有什么更好的东西值得值得打破了兼容性.)
(Next question: why this weird hack with the function I
and everything? The answer to that is that this is how R did it 30 years ago, and I couldn't think of anything sufficiently better to be worth breaking compatibility.)
这篇关于麻痹的倒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!