-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
Add support for math functions in eval() #10953
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+212
−19
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -38,6 +38,7 @@ Highlights include: | |
- Development installed versions of pandas will now have ``PEP440`` compliant version strings (:issue:`9518`) | ||
- Support for reading SAS xport files, see :ref:`here <whatsnew_0170.enhancements.sas_xport>` | ||
- Removal of the automatic TimeSeries broadcasting, deprecated since 0.8.0, see :ref:`here <whatsnew_0170.prior_deprecations>` | ||
- Support for math functions in .eval(), see :ref:`here <whatsnew_0170.matheval>` | ||
|
||
Check the :ref:`API Changes <whatsnew_0170.api>` and :ref:`deprecations <whatsnew_0170.deprecations>` before updating. | ||
|
||
|
@@ -123,6 +124,25 @@ incrementally. | |
|
||
See the :ref:`docs <io.sas>` for more details. | ||
|
||
.. _whatsnew_0170.matheval: | ||
|
||
Support for Math Functions in .eval() | ||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. add a |
||
:meth:`~pandas.eval` now supports calling math functions. | ||
|
||
.. code-block:: python | ||
|
||
df = pd.DataFrame({'a': np.random.randn(10)}) | ||
df.eval("b = sin(a)") | ||
|
||
The support math functions are `sin`, `cos`, `exp`, `log`, `expm1`, `log1p`, | ||
`sqrt`, `sinh`, `cosh`, `tanh`, `arcsin`, `arccos`, `arctan`, `arccosh`, | ||
`arcsinh`, `arctanh`, `abs` and `arctan2`. | ||
|
||
These functions map to the intrinsics for the NumExpr engine. For Python | ||
engine, they are mapped to NumPy calls. | ||
|
||
.. _whatsnew_0170.enhancements.other: | ||
|
||
Other enhancements | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,7 +23,8 @@ | |
from pandas.computation.expr import PythonExprVisitor, PandasExprVisitor | ||
from pandas.computation.ops import (_binary_ops_dict, | ||
_special_case_arith_ops_syms, | ||
_arith_ops_syms, _bool_ops_syms) | ||
_arith_ops_syms, _bool_ops_syms, | ||
_unary_math_ops, _binary_math_ops) | ||
|
||
import pandas.computation.expr as expr | ||
import pandas.util.testing as tm | ||
|
@@ -1439,6 +1440,129 @@ def setUpClass(cls): | |
cls.arith_ops = expr._arith_ops_syms + expr._cmp_ops_syms | ||
|
||
|
||
class TestMathPythonPython(tm.TestCase): | ||
@classmethod | ||
def setUpClass(cls): | ||
super(TestMathPythonPython, cls).setUpClass() | ||
tm.skip_if_no_ne() | ||
cls.engine = 'python' | ||
cls.parser = 'pandas' | ||
cls.unary_fns = _unary_math_ops | ||
cls.binary_fns = _binary_math_ops | ||
|
||
@classmethod | ||
def tearDownClass(cls): | ||
del cls.engine, cls.parser | ||
|
||
def eval(self, *args, **kwargs): | ||
kwargs['engine'] = self.engine | ||
kwargs['parser'] = self.parser | ||
kwargs['level'] = kwargs.pop('level', 0) + 1 | ||
return pd.eval(*args, **kwargs) | ||
|
||
def test_unary_functions(self): | ||
df = DataFrame({'a': np.random.randn(10)}) | ||
a = df.a | ||
for fn in self.unary_fns: | ||
expr = "{0}(a)".format(fn) | ||
got = self.eval(expr) | ||
expect = getattr(np, fn)(a) | ||
pd.util.testing.assert_almost_equal(got, expect) | ||
|
||
def test_binary_functions(self): | ||
df = DataFrame({'a': np.random.randn(10), | ||
'b': np.random.randn(10)}) | ||
a = df.a | ||
b = df.b | ||
for fn in self.binary_fns: | ||
expr = "{0}(a, b)".format(fn) | ||
got = self.eval(expr) | ||
expect = getattr(np, fn)(a, b) | ||
np.testing.assert_allclose(got, expect) | ||
|
||
def test_df_use_case(self): | ||
df = DataFrame({'a': np.random.randn(10), | ||
'b': np.random.randn(10)}) | ||
df.eval("e = arctan2(sin(a), b)", | ||
engine=self.engine, | ||
parser=self.parser) | ||
got = df.e | ||
expect = np.arctan2(np.sin(df.a), df.b) | ||
pd.util.testing.assert_almost_equal(got, expect) | ||
|
||
def test_df_arithmetic_subexpression(self): | ||
df = DataFrame({'a': np.random.randn(10), | ||
'b': np.random.randn(10)}) | ||
df.eval("e = sin(a + b)", | ||
engine=self.engine, | ||
parser=self.parser) | ||
got = df.e | ||
expect = np.sin(df.a + df.b) | ||
pd.util.testing.assert_almost_equal(got, expect) | ||
|
||
def check_result_type(self, dtype, expect_dtype): | ||
df = DataFrame({'a': np.random.randn(10).astype(dtype)}) | ||
self.assertEqual(df.a.dtype, dtype) | ||
df.eval("b = sin(a)", | ||
engine=self.engine, | ||
parser=self.parser) | ||
got = df.b | ||
expect = np.sin(df.a) | ||
self.assertEqual(expect.dtype, got.dtype) | ||
self.assertEqual(expect_dtype, got.dtype) | ||
pd.util.testing.assert_almost_equal(got, expect) | ||
|
||
def test_result_types(self): | ||
self.check_result_type(np.int32, np.float64) | ||
self.check_result_type(np.int64, np.float64) | ||
self.check_result_type(np.float32, np.float32) | ||
self.check_result_type(np.float64, np.float64) | ||
# Did not test complex64 because DataFrame is converting it to | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I merged the fix for #10952. if you'd add this test, would be great. ping when green. |
||
# complex128. Due to https://github.com/pydata/pandas/issues/10952 | ||
self.check_result_type(np.complex128, np.complex128) | ||
|
||
def test_undefined_func(self): | ||
df = DataFrame({'a': np.random.randn(10)}) | ||
with tm.assertRaisesRegexp(ValueError, | ||
"\"mysin\" is not a supported function"): | ||
df.eval("mysin(a)", | ||
engine=self.engine, | ||
parser=self.parser) | ||
|
||
def test_keyword_arg(self): | ||
df = DataFrame({'a': np.random.randn(10)}) | ||
with tm.assertRaisesRegexp(TypeError, | ||
"Function \"sin\" does not support " | ||
"keyword arguments"): | ||
df.eval("sin(x=a)", | ||
engine=self.engine, | ||
parser=self.parser) | ||
|
||
|
||
class TestMathPythonPandas(TestMathPythonPython): | ||
@classmethod | ||
def setUpClass(cls): | ||
super(TestMathPythonPandas, cls).setUpClass() | ||
cls.engine = 'python' | ||
cls.parser = 'pandas' | ||
|
||
|
||
class TestMathNumExprPandas(TestMathPythonPython): | ||
@classmethod | ||
def setUpClass(cls): | ||
super(TestMathNumExprPandas, cls).setUpClass() | ||
cls.engine = 'numexpr' | ||
cls.parser = 'pandas' | ||
|
||
|
||
class TestMathNumExprPython(TestMathPythonPython): | ||
@classmethod | ||
def setUpClass(cls): | ||
super(TestMathNumExprPython, cls).setUpClass() | ||
cls.engine = 'numexpr' | ||
cls.parser = 'python' | ||
|
||
|
||
_var_s = randn(10) | ||
|
||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pls add the issue number here as well.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pls move to the Enhancements section