forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_eval.py
1905 lines (1545 loc) · 68.2 KB
/
test_eval.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from distutils.version import LooseVersion
from itertools import product
import operator
import warnings
import numpy as np
from numpy.random import rand, randint, randn
import pytest
from pandas.compat import PY3, reduce
from pandas.errors import PerformanceWarning
import pandas.util._test_decorators as td
from pandas.core.dtypes.common import is_bool, is_list_like, is_scalar
import pandas as pd
from pandas import DataFrame, Series, date_range
from pandas.core.computation import pytables
from pandas.core.computation.check import _NUMEXPR_VERSION
from pandas.core.computation.engines import NumExprClobberingError, _engines
import pandas.core.computation.expr as expr
from pandas.core.computation.expr import PandasExprVisitor, PythonExprVisitor
from pandas.core.computation.expressions import (
_NUMEXPR_INSTALLED, _USE_NUMEXPR)
from pandas.core.computation.ops import (
_arith_ops_syms, _binary_math_ops, _binary_ops_dict,
_special_case_arith_ops_syms, _unary_math_ops)
import pandas.util.testing as tm
from pandas.util.testing import (
assert_frame_equal, assert_numpy_array_equal, assert_produces_warning,
assert_series_equal, makeCustomDataframe as mkdf, randbool)
@pytest.fixture(params=(
pytest.param(engine,
marks=pytest.mark.skipif(
engine == 'numexpr' and not _USE_NUMEXPR,
reason='numexpr enabled->{enabled}, '
'installed->{installed}'.format(
enabled=_USE_NUMEXPR,
installed=_NUMEXPR_INSTALLED)))
for engine in _engines)) # noqa
def engine(request):
return request.param
@pytest.fixture(params=expr._parsers)
def parser(request):
return request.param
@pytest.fixture
def ne_lt_2_6_9():
if _NUMEXPR_INSTALLED and _NUMEXPR_VERSION >= LooseVersion('2.6.9'):
pytest.skip("numexpr is >= 2.6.9")
return 'numexpr'
@pytest.fixture
def unary_fns_for_ne():
if _NUMEXPR_INSTALLED:
if _NUMEXPR_VERSION >= LooseVersion('2.6.9'):
return _unary_math_ops
else:
return tuple(x for x in _unary_math_ops
if x not in ("floor", "ceil"))
else:
pytest.skip("numexpr is not present")
def engine_has_neg_frac(engine):
return _engines[engine].has_neg_frac
def _eval_single_bin(lhs, cmp1, rhs, engine):
c = _binary_ops_dict[cmp1]
if engine_has_neg_frac(engine):
try:
return c(lhs, rhs)
except ValueError as e:
if str(e).startswith('negative number cannot be '
'raised to a fractional power'):
return np.nan
raise
return c(lhs, rhs)
def _series_and_2d_ndarray(lhs, rhs):
return ((isinstance(lhs, Series) and
isinstance(rhs, np.ndarray) and rhs.ndim > 1) or
(isinstance(rhs, Series) and
isinstance(lhs, np.ndarray) and lhs.ndim > 1))
def _series_and_frame(lhs, rhs):
return ((isinstance(lhs, Series) and isinstance(rhs, DataFrame)) or
(isinstance(rhs, Series) and isinstance(lhs, DataFrame)))
def _bool_and_frame(lhs, rhs):
return isinstance(lhs, bool) and isinstance(rhs, pd.core.generic.NDFrame)
def _is_py3_complex_incompat(result, expected):
return (PY3 and isinstance(expected, (complex, np.complexfloating)) and
np.isnan(result))
_good_arith_ops = set(_arith_ops_syms).difference(_special_case_arith_ops_syms)
@td.skip_if_no_ne
class TestEvalNumexprPandas(object):
@classmethod
def setup_class(cls):
import numexpr as ne
cls.ne = ne
cls.engine = 'numexpr'
cls.parser = 'pandas'
@classmethod
def teardown_class(cls):
del cls.engine, cls.parser
if hasattr(cls, 'ne'):
del cls.ne
def setup_data(self):
nan_df1 = DataFrame(rand(10, 5))
nan_df1[nan_df1 > 0.5] = np.nan
nan_df2 = DataFrame(rand(10, 5))
nan_df2[nan_df2 > 0.5] = np.nan
self.pandas_lhses = (DataFrame(randn(10, 5)), Series(randn(5)),
Series([1, 2, np.nan, np.nan, 5]), nan_df1)
self.pandas_rhses = (DataFrame(randn(10, 5)), Series(randn(5)),
Series([1, 2, np.nan, np.nan, 5]), nan_df2)
self.scalar_lhses = randn(),
self.scalar_rhses = randn(),
self.lhses = self.pandas_lhses + self.scalar_lhses
self.rhses = self.pandas_rhses + self.scalar_rhses
def setup_ops(self):
self.cmp_ops = expr._cmp_ops_syms
self.cmp2_ops = self.cmp_ops[::-1]
self.bin_ops = expr._bool_ops_syms
self.special_case_ops = _special_case_arith_ops_syms
self.arith_ops = _good_arith_ops
self.unary_ops = '-', '~', 'not '
def setup_method(self, method):
self.setup_ops()
self.setup_data()
self.current_engines = filter(lambda x: x != self.engine, _engines)
def teardown_method(self, method):
del self.lhses, self.rhses, self.scalar_rhses, self.scalar_lhses
del self.pandas_rhses, self.pandas_lhses, self.current_engines
@pytest.mark.slow
@pytest.mark.parametrize('cmp1', ['!=', '==', '<=', '>=', '<', '>'],
ids=['ne', 'eq', 'le', 'ge', 'lt', 'gt'])
@pytest.mark.parametrize('cmp2', ['>', '<'], ids=['gt', 'lt'])
def test_complex_cmp_ops(self, cmp1, cmp2):
for lhs, rhs, binop in product(
self.lhses, self.rhses, self.bin_ops):
lhs_new = _eval_single_bin(lhs, cmp1, rhs, self.engine)
rhs_new = _eval_single_bin(lhs, cmp2, rhs, self.engine)
expected = _eval_single_bin(
lhs_new, binop, rhs_new, self.engine)
ex = '(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)'.format(
cmp1=cmp1, binop=binop, cmp2=cmp2)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
self.check_equal(result, expected)
def test_simple_cmp_ops(self):
bool_lhses = (DataFrame(randbool(size=(10, 5))),
Series(randbool((5,))), randbool())
bool_rhses = (DataFrame(randbool(size=(10, 5))),
Series(randbool((5,))), randbool())
for lhs, rhs, cmp_op in product(bool_lhses, bool_rhses, self.cmp_ops):
self.check_simple_cmp_op(lhs, cmp_op, rhs)
@pytest.mark.slow
def test_binary_arith_ops(self):
for lhs, op, rhs in product(self.lhses, self.arith_ops, self.rhses):
self.check_binary_arith_op(lhs, op, rhs)
def test_modulus(self):
for lhs, rhs in product(self.lhses, self.rhses):
self.check_modulus(lhs, '%', rhs)
def test_floor_division(self):
for lhs, rhs in product(self.lhses, self.rhses):
self.check_floor_division(lhs, '//', rhs)
@td.skip_if_windows
def test_pow(self):
# odd failure on win32 platform, so skip
for lhs, rhs in product(self.lhses, self.rhses):
self.check_pow(lhs, '**', rhs)
@pytest.mark.slow
def test_single_invert_op(self):
for lhs, op, rhs in product(self.lhses, self.cmp_ops, self.rhses):
self.check_single_invert_op(lhs, op, rhs)
@pytest.mark.slow
def test_compound_invert_op(self):
for lhs, op, rhs in product(self.lhses, self.cmp_ops, self.rhses):
self.check_compound_invert_op(lhs, op, rhs)
@pytest.mark.slow
def test_chained_cmp_op(self):
mids = self.lhses
cmp_ops = '<', '>'
for lhs, cmp1, mid, cmp2, rhs in product(self.lhses, cmp_ops,
mids, cmp_ops, self.rhses):
self.check_chained_cmp_op(lhs, cmp1, mid, cmp2, rhs)
def check_equal(self, result, expected):
if isinstance(result, DataFrame):
tm.assert_frame_equal(result, expected)
elif isinstance(result, Series):
tm.assert_series_equal(result, expected)
elif isinstance(result, np.ndarray):
tm.assert_numpy_array_equal(result, expected)
else:
assert result == expected
def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs):
def check_operands(left, right, cmp_op):
return _eval_single_bin(left, cmp_op, right, self.engine)
lhs_new = check_operands(lhs, mid, cmp1)
rhs_new = check_operands(mid, rhs, cmp2)
if lhs_new is not None and rhs_new is not None:
ex1 = 'lhs {0} mid {1} rhs'.format(cmp1, cmp2)
ex2 = 'lhs {0} mid and mid {1} rhs'.format(cmp1, cmp2)
ex3 = '(lhs {0} mid) & (mid {1} rhs)'.format(cmp1, cmp2)
expected = _eval_single_bin(lhs_new, '&', rhs_new, self.engine)
for ex in (ex1, ex2, ex3):
result = pd.eval(ex, engine=self.engine,
parser=self.parser)
tm.assert_almost_equal(result, expected)
def check_simple_cmp_op(self, lhs, cmp1, rhs):
ex = 'lhs {0} rhs'.format(cmp1)
msg = (r"only list-like( or dict-like)? objects are allowed to be"
r" passed to (DataFrame\.)?isin\(\), you passed a"
r" (\[|')bool(\]|')|"
"argument of type 'bool' is not iterable")
if cmp1 in ('in', 'not in') and not is_list_like(rhs):
with pytest.raises(TypeError, match=msg):
pd.eval(ex, engine=self.engine, parser=self.parser,
local_dict={'lhs': lhs, 'rhs': rhs})
else:
expected = _eval_single_bin(lhs, cmp1, rhs, self.engine)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
self.check_equal(result, expected)
def check_binary_arith_op(self, lhs, arith1, rhs):
ex = 'lhs {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = _eval_single_bin(lhs, arith1, rhs, self.engine)
tm.assert_almost_equal(result, expected)
ex = 'lhs {0} rhs {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
nlhs = _eval_single_bin(lhs, arith1, rhs,
self.engine)
self.check_alignment(result, nlhs, rhs, arith1)
def check_alignment(self, result, nlhs, ghs, op):
try:
nlhs, ghs = nlhs.align(ghs)
except (ValueError, TypeError, AttributeError):
# ValueError: series frame or frame series align
# TypeError, AttributeError: series or frame with scalar align
pass
else:
# direct numpy comparison
expected = self.ne.evaluate('nlhs {0} ghs'.format(op))
tm.assert_numpy_array_equal(result.values, expected)
# modulus, pow, and floor division require special casing
def check_modulus(self, lhs, arith1, rhs):
ex = 'lhs {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = lhs % rhs
tm.assert_almost_equal(result, expected)
expected = self.ne.evaluate('expected {0} rhs'.format(arith1))
if isinstance(result, (DataFrame, Series)):
tm.assert_almost_equal(result.values, expected)
else:
tm.assert_almost_equal(result, expected.item())
def check_floor_division(self, lhs, arith1, rhs):
ex = 'lhs {0} rhs'.format(arith1)
if self.engine == 'python':
res = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = lhs // rhs
self.check_equal(res, expected)
else:
msg = (r"unsupported operand type\(s\) for //: 'VariableNode' and"
" 'VariableNode'")
with pytest.raises(TypeError, match=msg):
pd.eval(ex, local_dict={'lhs': lhs, 'rhs': rhs},
engine=self.engine, parser=self.parser)
def get_expected_pow_result(self, lhs, rhs):
try:
expected = _eval_single_bin(lhs, '**', rhs, self.engine)
except ValueError as e:
if str(e).startswith('negative number cannot be '
'raised to a fractional power'):
if self.engine == 'python':
pytest.skip(str(e))
else:
expected = np.nan
else:
raise
return expected
def check_pow(self, lhs, arith1, rhs):
ex = 'lhs {0} rhs'.format(arith1)
expected = self.get_expected_pow_result(lhs, rhs)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
if (is_scalar(lhs) and is_scalar(rhs) and
_is_py3_complex_incompat(result, expected)):
pytest.raises(AssertionError, tm.assert_numpy_array_equal,
result, expected)
else:
tm.assert_almost_equal(result, expected)
ex = '(lhs {0} rhs) {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = self.get_expected_pow_result(
self.get_expected_pow_result(lhs, rhs), rhs)
tm.assert_almost_equal(result, expected)
def check_single_invert_op(self, lhs, cmp1, rhs):
# simple
for el in (lhs, rhs):
try:
elb = el.astype(bool)
except AttributeError:
elb = np.array([bool(el)])
expected = ~elb
result = pd.eval('~elb', engine=self.engine, parser=self.parser)
tm.assert_almost_equal(expected, result)
for engine in self.current_engines:
tm.assert_almost_equal(result, pd.eval('~elb', engine=engine,
parser=self.parser))
def check_compound_invert_op(self, lhs, cmp1, rhs):
skip_these = 'in', 'not in'
ex = '~(lhs {0} rhs)'.format(cmp1)
msg = (r"only list-like( or dict-like)? objects are allowed to be"
r" passed to (DataFrame\.)?isin\(\), you passed a"
r" (\[|')float(\]|')|"
"argument of type 'float' is not iterable")
if is_scalar(rhs) and cmp1 in skip_these:
with pytest.raises(TypeError, match=msg):
pd.eval(ex, engine=self.engine, parser=self.parser,
local_dict={'lhs': lhs, 'rhs': rhs})
else:
# compound
if is_scalar(lhs) and is_scalar(rhs):
lhs, rhs = map(lambda x: np.array([x]), (lhs, rhs))
expected = _eval_single_bin(lhs, cmp1, rhs, self.engine)
if is_scalar(expected):
expected = not expected
else:
expected = ~expected
result = pd.eval(ex, engine=self.engine, parser=self.parser)
tm.assert_almost_equal(expected, result)
# make sure the other engines work the same as this one
for engine in self.current_engines:
ev = pd.eval(ex, engine=self.engine, parser=self.parser)
tm.assert_almost_equal(ev, result)
def ex(self, op, var_name='lhs'):
return '{0}{1}'.format(op, var_name)
def test_frame_invert(self):
expr = self.ex('~')
# ~ ##
# frame
# float always raises
lhs = DataFrame(randn(5, 2))
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
with pytest.raises(TypeError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
# int raises on numexpr
lhs = DataFrame(randint(5, size=(5, 2)))
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
expect = ~lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# bool always works
lhs = DataFrame(rand(5, 2) > 0.5)
expect = ~lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# object raises
lhs = DataFrame({'b': ['a', 1, 2.0], 'c': rand(3) > 0.5})
if self.engine == 'numexpr':
with pytest.raises(ValueError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
with pytest.raises(TypeError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
def test_series_invert(self):
# ~ ####
expr = self.ex('~')
# series
# float raises
lhs = Series(randn(5))
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
with pytest.raises(TypeError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
# int raises on numexpr
lhs = Series(randint(5, size=5))
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
expect = ~lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# bool
lhs = Series(rand(5) > 0.5)
expect = ~lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# float
# int
# bool
# object
lhs = Series(['a', 1, 2.0])
if self.engine == 'numexpr':
with pytest.raises(ValueError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
with pytest.raises(TypeError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
def test_frame_negate(self):
expr = self.ex('-')
# float
lhs = DataFrame(randn(5, 2))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# int
lhs = DataFrame(randint(5, size=(5, 2)))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# bool doesn't work with numexpr but works elsewhere
lhs = DataFrame(rand(5, 2) > 0.5)
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
def test_series_negate(self):
expr = self.ex('-')
# float
lhs = Series(randn(5))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# int
lhs = Series(randint(5, size=5))
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# bool doesn't work with numexpr but works elsewhere
lhs = Series(rand(5) > 0.5)
if self.engine == 'numexpr':
with pytest.raises(NotImplementedError):
result = pd.eval(expr, engine=self.engine, parser=self.parser)
else:
expect = -lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
def test_frame_pos(self):
expr = self.ex('+')
# float
lhs = DataFrame(randn(5, 2))
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# int
lhs = DataFrame(randint(5, size=(5, 2)))
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
# bool doesn't work with numexpr but works elsewhere
lhs = DataFrame(rand(5, 2) > 0.5)
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_frame_equal(expect, result)
def test_series_pos(self):
expr = self.ex('+')
# float
lhs = Series(randn(5))
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# int
lhs = Series(randint(5, size=5))
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
# bool doesn't work with numexpr but works elsewhere
lhs = Series(rand(5) > 0.5)
expect = lhs
result = pd.eval(expr, engine=self.engine, parser=self.parser)
assert_series_equal(expect, result)
def test_scalar_unary(self):
with pytest.raises(TypeError):
pd.eval('~1.0', engine=self.engine, parser=self.parser)
assert pd.eval('-1.0', parser=self.parser,
engine=self.engine) == -1.0
assert pd.eval('+1.0', parser=self.parser,
engine=self.engine) == +1.0
assert pd.eval('~1', parser=self.parser,
engine=self.engine) == ~1
assert pd.eval('-1', parser=self.parser,
engine=self.engine) == -1
assert pd.eval('+1', parser=self.parser,
engine=self.engine) == +1
assert pd.eval('~True', parser=self.parser,
engine=self.engine) == ~True
assert pd.eval('~False', parser=self.parser,
engine=self.engine) == ~False
assert pd.eval('-True', parser=self.parser,
engine=self.engine) == -True
assert pd.eval('-False', parser=self.parser,
engine=self.engine) == -False
assert pd.eval('+True', parser=self.parser,
engine=self.engine) == +True
assert pd.eval('+False', parser=self.parser,
engine=self.engine) == +False
def test_unary_in_array(self):
# GH 11235
assert_numpy_array_equal(
pd.eval('[-True, True, ~True, +True,'
'-False, False, ~False, +False,'
'-37, 37, ~37, +37]'),
np.array([-True, True, ~True, +True,
-False, False, ~False, +False,
-37, 37, ~37, +37], dtype=np.object_))
def test_disallow_scalar_bool_ops(self):
exprs = '1 or 2', '1 and 2'
exprs += 'a and b', 'a or b'
exprs += '1 or 2 and (3 + 2) > 3',
exprs += '2 * x > 2 or 1 and 2',
exprs += '2 * df > 3 and 1 or a',
x, a, b, df = np.random.randn(3), 1, 2, DataFrame(randn(3, 2)) # noqa
for ex in exprs:
with pytest.raises(NotImplementedError):
pd.eval(ex, engine=self.engine, parser=self.parser)
def test_identical(self):
# see gh-10546
x = 1
result = pd.eval('x', engine=self.engine, parser=self.parser)
assert result == 1
assert is_scalar(result)
x = 1.5
result = pd.eval('x', engine=self.engine, parser=self.parser)
assert result == 1.5
assert is_scalar(result)
x = False
result = pd.eval('x', engine=self.engine, parser=self.parser)
assert not result
assert is_bool(result)
assert is_scalar(result)
x = np.array([1])
result = pd.eval('x', engine=self.engine, parser=self.parser)
tm.assert_numpy_array_equal(result, np.array([1]))
assert result.shape == (1, )
x = np.array([1.5])
result = pd.eval('x', engine=self.engine, parser=self.parser)
tm.assert_numpy_array_equal(result, np.array([1.5]))
assert result.shape == (1, )
x = np.array([False]) # noqa
result = pd.eval('x', engine=self.engine, parser=self.parser)
tm.assert_numpy_array_equal(result, np.array([False]))
assert result.shape == (1, )
def test_line_continuation(self):
# GH 11149
exp = """1 + 2 * \
5 - 1 + 2 """
result = pd.eval(exp, engine=self.engine, parser=self.parser)
assert result == 12
def test_float_truncation(self):
# GH 14241
exp = '1000000000.006'
result = pd.eval(exp, engine=self.engine, parser=self.parser)
expected = np.float64(exp)
assert result == expected
df = pd.DataFrame({'A': [1000000000.0009,
1000000000.0011,
1000000000.0015]})
cutoff = 1000000000.0006
result = df.query("A < %.4f" % cutoff)
assert result.empty
cutoff = 1000000000.0010
result = df.query("A > %.4f" % cutoff)
expected = df.loc[[1, 2], :]
tm.assert_frame_equal(expected, result)
exact = 1000000000.0011
result = df.query('A == %.4f' % exact)
expected = df.loc[[1], :]
tm.assert_frame_equal(expected, result)
def test_disallow_python_keywords(self):
# GH 18221
df = pd.DataFrame([[0, 0, 0]], columns=['foo', 'bar', 'class'])
msg = "Python keyword not valid identifier in numexpr query"
with pytest.raises(SyntaxError, match=msg):
df.query('class == 0')
df = pd.DataFrame()
df.index.name = 'lambda'
with pytest.raises(SyntaxError, match=msg):
df.query('lambda == 0')
@td.skip_if_no_ne
class TestEvalNumexprPython(TestEvalNumexprPandas):
@classmethod
def setup_class(cls):
super(TestEvalNumexprPython, cls).setup_class()
import numexpr as ne
cls.ne = ne
cls.engine = 'numexpr'
cls.parser = 'python'
def setup_ops(self):
self.cmp_ops = list(filter(lambda x: x not in ('in', 'not in'),
expr._cmp_ops_syms))
self.cmp2_ops = self.cmp_ops[::-1]
self.bin_ops = [s for s in expr._bool_ops_syms
if s not in ('and', 'or')]
self.special_case_ops = _special_case_arith_ops_syms
self.arith_ops = _good_arith_ops
self.unary_ops = '+', '-', '~'
def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs):
ex1 = 'lhs {0} mid {1} rhs'.format(cmp1, cmp2)
with pytest.raises(NotImplementedError):
pd.eval(ex1, engine=self.engine, parser=self.parser)
class TestEvalPythonPython(TestEvalNumexprPython):
@classmethod
def setup_class(cls):
super(TestEvalPythonPython, cls).setup_class()
cls.engine = 'python'
cls.parser = 'python'
def check_modulus(self, lhs, arith1, rhs):
ex = 'lhs {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = lhs % rhs
tm.assert_almost_equal(result, expected)
expected = _eval_single_bin(expected, arith1, rhs, self.engine)
tm.assert_almost_equal(result, expected)
def check_alignment(self, result, nlhs, ghs, op):
try:
nlhs, ghs = nlhs.align(ghs)
except (ValueError, TypeError, AttributeError):
# ValueError: series frame or frame series align
# TypeError, AttributeError: series or frame with scalar align
pass
else:
expected = eval('nlhs {0} ghs'.format(op))
tm.assert_almost_equal(result, expected)
class TestEvalPythonPandas(TestEvalPythonPython):
@classmethod
def setup_class(cls):
super(TestEvalPythonPandas, cls).setup_class()
cls.engine = 'python'
cls.parser = 'pandas'
def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs):
TestEvalNumexprPandas.check_chained_cmp_op(self, lhs, cmp1, mid, cmp2,
rhs)
f = lambda *args, **kwargs: np.random.randn()
# -------------------------------------
# gh-12388: Typecasting rules consistency with python
class TestTypeCasting(object):
@pytest.mark.parametrize('op', ['+', '-', '*', '**', '/'])
# maybe someday... numexpr has too many upcasting rules now
# chain(*(np.sctypes[x] for x in ['uint', 'int', 'float']))
@pytest.mark.parametrize('dt', [np.float32, np.float64])
def test_binop_typecasting(self, engine, parser, op, dt):
df = mkdf(5, 3, data_gen_f=f, dtype=dt)
s = 'df {} 3'.format(op)
res = pd.eval(s, engine=engine, parser=parser)
assert df.values.dtype == dt
assert res.values.dtype == dt
assert_frame_equal(res, eval(s))
s = '3 {} df'.format(op)
res = pd.eval(s, engine=engine, parser=parser)
assert df.values.dtype == dt
assert res.values.dtype == dt
assert_frame_equal(res, eval(s))
# -------------------------------------
# Basic and complex alignment
def _is_datetime(x):
return issubclass(x.dtype.type, np.datetime64)
def should_warn(*args):
not_mono = not any(map(operator.attrgetter('is_monotonic'), args))
only_one_dt = reduce(operator.xor, map(_is_datetime, args))
return not_mono and only_one_dt
class TestAlignment(object):
index_types = 'i', 'u', 'dt'
lhs_index_types = index_types + ('s',) # 'p'
def test_align_nested_unary_op(self, engine, parser):
s = 'df * ~2'
df = mkdf(5, 3, data_gen_f=f)
res = pd.eval(s, engine=engine, parser=parser)
assert_frame_equal(res, df * ~2)
def test_basic_frame_alignment(self, engine, parser):
args = product(self.lhs_index_types, self.index_types,
self.index_types)
with warnings.catch_warnings(record=True):
warnings.simplefilter('always', RuntimeWarning)
for lr_idx_type, rr_idx_type, c_idx_type in args:
df = mkdf(10, 10, data_gen_f=f, r_idx_type=lr_idx_type,
c_idx_type=c_idx_type)
df2 = mkdf(20, 10, data_gen_f=f, r_idx_type=rr_idx_type,
c_idx_type=c_idx_type)
# only warns if not monotonic and not sortable
if should_warn(df.index, df2.index):
with tm.assert_produces_warning(RuntimeWarning):
res = pd.eval('df + df2', engine=engine, parser=parser)
else:
res = pd.eval('df + df2', engine=engine, parser=parser)
assert_frame_equal(res, df + df2)
def test_frame_comparison(self, engine, parser):
args = product(self.lhs_index_types, repeat=2)
for r_idx_type, c_idx_type in args:
df = mkdf(10, 10, data_gen_f=f, r_idx_type=r_idx_type,
c_idx_type=c_idx_type)
res = pd.eval('df < 2', engine=engine, parser=parser)
assert_frame_equal(res, df < 2)
df3 = DataFrame(randn(*df.shape), index=df.index,
columns=df.columns)
res = pd.eval('df < df3', engine=engine, parser=parser)
assert_frame_equal(res, df < df3)
@pytest.mark.slow
def test_medium_complex_frame_alignment(self, engine, parser):
args = product(self.lhs_index_types, self.index_types,
self.index_types, self.index_types)
with warnings.catch_warnings(record=True):
warnings.simplefilter('always', RuntimeWarning)
for r1, c1, r2, c2 in args:
df = mkdf(3, 2, data_gen_f=f, r_idx_type=r1, c_idx_type=c1)
df2 = mkdf(4, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2)
df3 = mkdf(5, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2)
if should_warn(df.index, df2.index, df3.index):
with tm.assert_produces_warning(RuntimeWarning):
res = pd.eval('df + df2 + df3', engine=engine,
parser=parser)
else:
res = pd.eval('df + df2 + df3',
engine=engine, parser=parser)
assert_frame_equal(res, df + df2 + df3)
def test_basic_frame_series_alignment(self, engine, parser):
def testit(r_idx_type, c_idx_type, index_name):
df = mkdf(10, 10, data_gen_f=f, r_idx_type=r_idx_type,
c_idx_type=c_idx_type)
index = getattr(df, index_name)
s = Series(np.random.randn(5), index[:5])
if should_warn(df.index, s.index):
with tm.assert_produces_warning(RuntimeWarning):
res = pd.eval('df + s', engine=engine, parser=parser)
else:
res = pd.eval('df + s', engine=engine, parser=parser)
if r_idx_type == 'dt' or c_idx_type == 'dt':
expected = df.add(s) if engine == 'numexpr' else df + s
else:
expected = df + s
assert_frame_equal(res, expected)
args = product(self.lhs_index_types, self.index_types,
('index', 'columns'))
with warnings.catch_warnings(record=True):
warnings.simplefilter('always', RuntimeWarning)
for r_idx_type, c_idx_type, index_name in args:
testit(r_idx_type, c_idx_type, index_name)
def test_basic_series_frame_alignment(self, engine, parser):
def testit(r_idx_type, c_idx_type, index_name):
df = mkdf(10, 7, data_gen_f=f, r_idx_type=r_idx_type,
c_idx_type=c_idx_type)
index = getattr(df, index_name)
s = Series(np.random.randn(5), index[:5])
if should_warn(s.index, df.index):
with tm.assert_produces_warning(RuntimeWarning):
res = pd.eval('s + df', engine=engine, parser=parser)
else:
res = pd.eval('s + df', engine=engine, parser=parser)
if r_idx_type == 'dt' or c_idx_type == 'dt':
expected = df.add(s) if engine == 'numexpr' else s + df
else:
expected = s + df
assert_frame_equal(res, expected)
# only test dt with dt, otherwise weird joins result
args = product(['i', 'u', 's'], ['i', 'u', 's'], ('index', 'columns'))
with warnings.catch_warnings(record=True):
# avoid warning about comparing strings and ints
warnings.simplefilter("ignore", RuntimeWarning)
for r_idx_type, c_idx_type, index_name in args:
testit(r_idx_type, c_idx_type, index_name)
# dt with dt
args = product(['dt'], ['dt'], ('index', 'columns'))
with warnings.catch_warnings(record=True):
# avoid warning about comparing strings and ints
warnings.simplefilter("ignore", RuntimeWarning)
for r_idx_type, c_idx_type, index_name in args:
testit(r_idx_type, c_idx_type, index_name)
def test_series_frame_commutativity(self, engine, parser):
args = product(self.lhs_index_types, self.index_types, ('+', '*'),
('index', 'columns'))
with warnings.catch_warnings(record=True):
warnings.simplefilter('always', RuntimeWarning)
for r_idx_type, c_idx_type, op, index_name in args:
df = mkdf(10, 10, data_gen_f=f, r_idx_type=r_idx_type,
c_idx_type=c_idx_type)
index = getattr(df, index_name)
s = Series(np.random.randn(5), index[:5])
lhs = 's {0} df'.format(op)
rhs = 'df {0} s'.format(op)
if should_warn(df.index, s.index):
with tm.assert_produces_warning(RuntimeWarning):
a = pd.eval(lhs, engine=engine, parser=parser)
with tm.assert_produces_warning(RuntimeWarning):
b = pd.eval(rhs, engine=engine, parser=parser)
else:
a = pd.eval(lhs, engine=engine, parser=parser)
b = pd.eval(rhs, engine=engine, parser=parser)
if r_idx_type != 'dt' and c_idx_type != 'dt':
if engine == 'numexpr':
assert_frame_equal(a, b)
@pytest.mark.slow
def test_complex_series_frame_alignment(self, engine, parser):
import random
args = product(self.lhs_index_types, self.index_types,
self.index_types, self.index_types)
n = 3
m1 = 5
m2 = 2 * m1
with warnings.catch_warnings(record=True):
warnings.simplefilter('always', RuntimeWarning)
for r1, r2, c1, c2 in args:
index_name = random.choice(['index', 'columns'])
obj_name = random.choice(['df', 'df2'])
df = mkdf(m1, n, data_gen_f=f, r_idx_type=r1, c_idx_type=c1)
df2 = mkdf(m2, n, data_gen_f=f, r_idx_type=r2, c_idx_type=c2)
index = getattr(locals().get(obj_name), index_name)
s = Series(np.random.randn(n), index[:n])
if r2 == 'dt' or c2 == 'dt':
if engine == 'numexpr':
expected2 = df2.add(s)
else:
expected2 = df2 + s
else:
expected2 = df2 + s
if r1 == 'dt' or c1 == 'dt':
if engine == 'numexpr':
expected = expected2.add(df)
else:
expected = expected2 + df
else:
expected = expected2 + df
if should_warn(df2.index, s.index, df.index):
with tm.assert_produces_warning(RuntimeWarning):
res = pd.eval('df2 + s + df', engine=engine,