How to use the patsy.eval.EvalEnvironment function in patsy

To help you get started, we’ve selected a few patsy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pydata / patsy / patsy / eval.py View on Github external
env2 = EvalEnvironment([{"a": 11}], flags=test_flag)
        assert env2.eval("a <> 0") == True
        assert_raises(SyntaxError, env2.eval, "a != 0")
        assert env2.subset(["a"]).flags == test_flag
        assert env2.with_outer_namespace({"b": 10}).flags == test_flag
    else:
        test_flag = __future__.division.compiler_flag
        assert test_flag & _ALL_FUTURE_FLAGS

        env = EvalEnvironment([{"a": 11}], flags=0)
        assert env.eval("a / 2") == 11 // 2 == 5
        assert env.subset(["a"]).flags == 0
        assert env.with_outer_namespace({"b": 10}).flags == 0

        env2 = EvalEnvironment([{"a": 11}], flags=test_flag)
        assert env2.eval("a / 2") == 11 * 1. / 2 != 5
        env2.subset(["a"]).flags == test_flag
        assert env2.with_outer_namespace({"b": 10}).flags == test_flag
github yhat / ggpy / ggplot / aes.py View on Github external
def _evaluate_expressions(self, data):
        """
        Evaluates patsy expressions within the aesthetics. For example, 'x + 1'
        , 'factor(x)', or 'pd.cut(price, bins=10)')
        """
        for key, item in self.data.items():
            if item not in data:
                def factor(s, levels=None, labels=None):
                    return s.apply(str)

                env = EvalEnvironment.capture(eval_env=(self.__eval_env__ or 1)).with_outer_namespace({ "factor": factor, "pd": pd, "np": np })
                try:
                    new_val = env.eval(item, inner_namespace=data)
                    data[item] = new_val
                except:
                    msg = "Invalid column: '%s'" % str(item)
                    matches = difflib.get_close_matches(item, data.columns)
                    msg += "\ndid you mean one of the following:\n"
                    for match in matches:
                        msg += "    - %s\n" % match
                    raise Exception(msg)
        return data
github pydata / patsy / patsy / eval.py View on Github external
def test_EvalEnvironment_subset():
    env = EvalEnvironment([{"a": 1}, {"b": 2}, {"c": 3}])

    subset_a = env.subset(["a"])
    assert subset_a.eval("a") == 1
    from nose.tools import assert_raises
    assert_raises(NameError, subset_a.eval, "b")
    assert_raises(NameError, subset_a.eval, "c")

    subset_bc = env.subset(["b", "c"])
    assert subset_bc.eval("b * c") == 6
    assert_raises(NameError, subset_bc.eval, "a")
github has2k1 / plotnine / plotnine / ggplot.py View on Github external
# Recognize plydata groups
        if hasattr(data, 'group_indices') and 'group' not in mapping:
            mapping = mapping.copy()
            mapping['group'] = data.group_indices()

        self.data = data
        self.mapping = mapping
        self.facet = facet_null()
        self.labels = make_labels(mapping)
        self.layers = Layers()
        self.guides = guides()
        self.scales = Scales()
        self.theme = None
        self.coordinates = coord_cartesian()
        self.environment = environment or EvalEnvironment.capture(1)
        self.layout = None
        self.figure = None
        self.watermarks = []
        self.axs = None
github pydata / patsy / patsy / highlevel.py View on Github external
# Included for the convenience of people who are using py2 with
        # __future__.unicode_literals.
        try:
            formula_like = formula_like.encode("ascii")
        except UnicodeEncodeError:
            raise PatsyError(
                "On Python 2, formula strings must be either 'str' objects, "
                "or else 'unicode' objects containing only ascii "
                "characters. You passed a unicode string with non-ascii "
                "characters. I'm afraid you'll have to either switch to "
                "ascii-only, or else upgrade to Python 3.")
    if isinstance(formula_like, str):
        formula_like = ModelDesc.from_formula(formula_like)
        # fallthrough
    if isinstance(formula_like, ModelDesc):
        assert isinstance(eval_env, EvalEnvironment)
        return design_matrix_builders([formula_like.lhs_termlist,
                                       formula_like.rhs_termlist],
                                      data_iter_maker,
                                      eval_env,
                                      NA_action)
    else:
        return None
github pydata / patsy / patsy / build.py View on Github external
This function performs zero or more iterations over the data in order to
    sniff out any necessary information about factor types, set up stateful
    transforms, pick column names, etc.

    See :ref:`formulas` for details.

    .. versionadded:: 0.2.0
       The ``NA_action`` argument.
    .. versionadded:: 0.4.0
       The ``eval_env`` argument.
    """
    # People upgrading from versions prior to 0.4.0 could potentially have
    # passed NA_action as the 3rd positional argument. Fortunately
    # EvalEnvironment.capture only accepts int and EvalEnvironment objects,
    # and we improved its error messages to make this clear.
    eval_env = EvalEnvironment.capture(eval_env, reference=1)
    if isinstance(NA_action, str):
        NA_action = NAAction(NA_action)
    all_factors = set()
    for termlist in termlists:
        for term in termlist:
            all_factors.update(term.factors)
    factor_states = _factors_memorize(all_factors, data_iter_maker, eval_env)
    # Now all the factors have working eval methods, so we can evaluate them
    # on some data to find out what type of data they return.
    (num_column_counts,
     cat_levels_contrasts) = _examine_factor_types(all_factors,
                                                   factor_states,
                                                   data_iter_maker,
                                                   NA_action)
    # Now we need the factor infos, which encapsulate the knowledge of
    # how to turn any given factor into a chunk of data:
github pydata / patsy / patsy / eval.py View on Github external
def test_EvalEnvironment_eval_namespace():
    env = EvalEnvironment([{"a": 1}])
    assert env.eval("2 * a") == 2
    assert env.eval("2 * a", inner_namespace={"a": 2}) == 4
    from nose.tools import assert_raises
    assert_raises(NameError, env.eval, "2 * b")
    a = 3
    env2 = EvalEnvironment.capture(0)
    assert env2.eval("2 * a") == 6

    env3 = env.with_outer_namespace({"a": 10, "b": 3})
    assert env3.eval("2 * a") == 2
    assert env3.eval("2 * b") == 6
github pydata / patsy / patsy / builtins.py View on Github external
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 ``Q`` is 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"))
    """
    from patsy.eval import EvalEnvironment
    env = EvalEnvironment.capture(1)
    try:
        return env.namespace[name]
    except KeyError:
        raise NameError("no data named %r found" % (name,))