2.1.3. patsy.builtins.Q¶
-
patsy.builtins.Q(name)[source]¶ A way to ‘quote’ variable names, especially ones that do not otherwise meet Python’s variable name rules.
If
xis a variable,Q("x")returns the value ofx. (Note thatQtakes the string"x", not the value ofxitself.) This works even if instead ofx, we have a variable name that would not otherwise be legal in Python.For example, if you have a column of data named
weight.in.kg, then you can’t write:y ~ weight.in.kg
because Python will try to find a variable named
weight, that has an attribute namedin, that has an attribute namedkg. (And worse yet,inis a reserved word, which makes this example doubly broken.) Instead, write:y ~ Q("weight.in.kg")and all will be well. Note, though, that this requires embedding a Python string inside your formula, which may require some care with your quote marks. Some standard options include:
my_fit_function("y ~ Q('weight.in.kg')", ...) my_fit_function('y ~ Q("weight.in.kg")', ...) my_fit_function("y ~ Q(\"weight.in.kg\")", ...)
Note also that
Qis an ordinary Python function, which means that you can use it in more complex expressions. For example, this is a legal formula:y ~ np.sqrt(Q("weight.in.kg"))