Repository navigation
Expand file tree
/
Copy pathhpat_pandas_dataframe_functions.py
More file actions
2970 lines (2303 loc) · 112 KB
/
Copy pathhpat_pandas_dataframe_functions.py
File metadata and controls
2970 lines (2303 loc) · 112 KB
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
# *****************************************************************************
# Copyright (c) 2019-2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
'''
| :class:`pandas.DataFrame` functions and operators implementations in Intel SDC
| Also, it contains Numba internal operators which are required for DataFrame type handling
'''
import numba
import numpy
import operator
import pandas
import sdc
from pandas.core.indexing import IndexingError
from numba import types
from numba import literally
from numba.typed import List, Dict
from numba.core.errors import TypingError
from pandas.core.indexing import IndexingError
from sdc.hiframes.pd_dataframe_ext import DataFrameType
from sdc.hiframes.pd_series_type import SeriesType
from sdc.utilities.sdc_typing_utils import (TypeChecker, check_index_is_numeric,
check_types_comparable, kwsparams2list,
gen_impl_generator, find_common_dtype_from_numpy_dtypes)
from sdc.str_arr_ext import StringArrayType
from sdc.hiframes.pd_dataframe_type import DataFrameType
from sdc.datatypes.hpat_pandas_dataframe_getitem_types import (DataFrameGetitemAccessorType,
dataframe_getitem_accessor_init)
from sdc.datatypes.common_functions import SDCLimitation
from sdc.datatypes.hpat_pandas_dataframe_rolling_types import _hpat_pandas_df_rolling_init
from sdc.datatypes.hpat_pandas_rolling_types import (
gen_sdc_pandas_rolling_overload_body, sdc_pandas_rolling_docstring_tmpl)
from sdc.datatypes.hpat_pandas_groupby_functions import init_dataframe_groupby, merge_groupby_dicts_inplace
from sdc.hiframes.pd_dataframe_ext import get_dataframe_data
from sdc.utilities.utils import sdc_overload, sdc_overload_method, sdc_overload_attribute
from sdc.hiframes.api import isna
from sdc.functions.numpy_like import getitem_by_mask
from sdc.datatypes.common_functions import _sdc_take, sdc_reindex_series
from sdc.utilities.prange_utils import parallel_chunks
from sdc.functions.numpy_like import find_idx
@sdc_overload_attribute(DataFrameType, 'index')
def hpat_pandas_dataframe_index(df):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.index
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_index.py
:language: python
:lines: 27-
:caption: The index (row labels) of the DataFrame.
:name: ex_dataframe_index
.. command-output:: python ./dataframe/dataframe_index.py
:cwd: ../../../examples
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame attribute :attr:`pandas.DataFrame.index` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_index*
"""
ty_checker = TypeChecker('Attribute index.')
ty_checker.check(df, DataFrameType)
if isinstance(df.index, types.NoneType) or df.index is None:
empty_df = not df.columns
def hpat_pandas_df_index_none_impl(df):
df_len = len(df._data[0]) if empty_df == False else 0 # noqa
return numpy.arange(df_len)
return hpat_pandas_df_index_none_impl
else:
def hpat_pandas_df_index_impl(df):
return df._index
return hpat_pandas_df_index_impl
def sdc_pandas_dataframe_values_codegen(self, numba_common_dtype):
"""
Example of generated implementation:
def sdc_pandas_dataframe_values_impl(self):
length = len(self._data[0][0])
col_data_0 = self._data[0][0]
col_data_1 = self._data[1][0]
col_data_2 = self._data[0][1]
values = numpy.empty(length*3, numpy.dtype("float64"))
for i in range(length):
values[i*3+0] = col_data_0[i]
values[i*3+1] = col_data_1[i]
values[i*3+2] = col_data_2[i]
return values.reshape(length, 3)
"""
columns_data = []
columns_num = len(self.columns)
func_lines = [
f'def sdc_pandas_dataframe_values_impl(self):',
f' length = {df_length_expr(self)}',
]
for i, col in enumerate(self.columns):
col_loc = self.column_loc[col]
type_id, col_id = col_loc.type_id, col_loc.col_id
func_lines += [
f' col_data_{i} = self._data[{type_id}][{col_id}]',
]
columns_data.append(f'col_data_{i}')
func_lines += [
f' values = numpy.empty(length*{columns_num}, numpy.dtype("{numba_common_dtype}"))',
f' for i in range(length):',
]
func_lines += ['\n'.join([
f' values[i*{columns_num}+{j}] = {columns_data[j]}[i]',
]) for j in range(columns_num)]
func_lines += [
f' return values.reshape(length, {columns_num})\n'
]
func_text = '\n'.join(func_lines)
global_vars = {'pandas': pandas, 'numpy': numpy}
return func_text, global_vars
@sdc_overload_attribute(DataFrameType, 'values')
def hpat_pandas_dataframe_values(self):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.values
Limitations
-----------
- Only numeric values supported as an output
- The dtype will be a lower-common-denominator dtype (implicit upcasting);
that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen.
Use this with care if you are not dealing with the blocks.
e.g. If the dtypes are float16 and float32, dtype will be upcast to float32. If dtypes are int32 and uint8,
dtype will be upcast to int32. By numpy.find_common_type() convention,
mixing int64 and uint64 will result in a float64 dtype.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_values.py
:language: python
:lines: 27-
:caption: The values data of the DataFrame.
:name: ex_dataframe_values
.. command-output:: python ./dataframe/dataframe_values.py
:cwd: ../../../examples
.. seealso::
:ref:`DataFrame.to_numpy <pandas.DataFrame.to_numpy>`
Recommended alternative to this method.
:ref:`DataFrame.index <pandas.DataFrame.index>`
Retrieve the index labels.
:ref:`DataFrame.columns <pandas.DataFrame.columns>`
Retrieving the column names.
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame attribute :attr:`pandas.DataFrame.values` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_df_values*
"""
func_name = 'Attribute values.'
ty_checker = TypeChecker(func_name)
ty_checker.check(self, DataFrameType)
# TODO: Handle StringArrayType
for i, column in enumerate(self.data):
if isinstance(column, StringArrayType):
ty_checker.raise_exc(column, 'Numeric type', f'df.data["{self.columns[i]}"]')
numba_common_dtype = find_common_dtype_from_numpy_dtypes([column.dtype for column in self.data], [])
def hpat_pandas_df_values_impl(self, numba_common_dtype):
loc_vars = {}
func_text, global_vars = sdc_pandas_dataframe_values_codegen(self, numba_common_dtype)
exec(func_text, global_vars, loc_vars)
_values_impl = loc_vars['sdc_pandas_dataframe_values_impl']
return _values_impl
return hpat_pandas_df_values_impl(self, numba_common_dtype)
def sdc_pandas_dataframe_append_codegen(df, other, _func_name, ignore_index_value, indexes_comparable, args):
"""
Example of generated implementation:
def sdc_pandas_dataframe_append_impl(df, other, ignore_index=False, verify_integrity=False, sort=None):
len_df = len(df._data[0][0])
len_other = len(other._data[0][0])
new_col_0_data_df = df._data[0][0]
new_col_0_data_other = other._data[0][0]
new_col_0 = init_series(new_col_0_data_df).append(init_series(new_col_0_data_other))._data
new_col_1_data_df = df._data[0][1]
new_col_1_data_other = other._data[0][1]
new_col_1 = init_series(new_col_1_data_df).append(init_series(new_col_1_data_other))._data
return pandas.DataFrame({"A": new_col_0, "B": new_col_1})
"""
indent = 4 * ' '
func_args = ['df', 'other'] + kwsparams2list(args)
df_columns_indx = {col_name: i for i, col_name in enumerate(df.columns)}
other_columns_indx = {col_name: i for i, col_name in enumerate(other.columns)}
# Keep columns that are StringArrayType
string_type_columns = set(col_name for typ, col_name in zip(df.data, df.columns)
if isinstance(typ, StringArrayType))
for typ, col_name in zip(other.data, other.columns):
if isinstance(typ, StringArrayType):
string_type_columns.add(col_name)
func_definition = [f'def sdc_pandas_dataframe_{_func_name}_impl({", ".join(func_args)}):']
func_text = []
column_list = []
func_text.append(f'len_df = len(df._data[0][0])')
func_text.append(f'len_other = len(other._data[0][0])')
for col_name, idx in df_columns_indx.items():
col_loc = df.column_loc[col_name]
type_id, col_id = col_loc.type_id, col_loc.col_id
func_text.append(f'new_col_{idx}_data_df = df._data[{type_id}][{col_id}]')
if col_name in other_columns_indx:
other_col_loc = other.column_loc[col_name]
other_type_id, other_col_id = other_col_loc.type_id, other_col_loc.col_id
func_text.append(f'new_col_{idx}_data_other = '
f'other._data[{other_type_id}][{other_col_id}]')
s1 = f'init_series(new_col_{idx}_data_df)'
s2 = f'init_series(new_col_{idx}_data_other)'
func_text.append(f'new_col_{idx} = {s1}.append({s2})._data')
else:
func_text.append(f'new_col_{idx}_data = init_series(new_col_{idx}_data_df)._data')
if col_name in string_type_columns:
func_text.append(f'new_col_{idx} = fill_str_array(new_col_{idx}_data, len_df+len_other)')
else:
func_text.append(f'new_col_{idx} = fill_array(new_col_{idx}_data, len_df+len_other)')
column_list.append((f'new_col_{idx}', col_name))
for col_name, idx in other_columns_indx.items():
if col_name not in df_columns_indx:
other_col_loc = other.column_loc[col_name]
other_type_id, other_col_id = other_col_loc.type_id, other_col_loc.col_id
func_text.append(f'new_col_{idx}_data_other = other._data[{other_type_id}][{other_col_id}]')
func_text.append(f'new_col_{idx}_data = init_series(new_col_{idx}_data_other)._data')
if col_name in string_type_columns:
func_text.append(
f'new_col_{idx}_other = '
f'fill_str_array(new_col_{idx}_data, len_df+len_other, push_back=False)')
else:
func_text.append(f'new_col_{idx}_other = '
f'fill_array(new_col_{idx}_data, len_df+len_other, push_back=False)')
column_list.append((f'new_col_{idx}_other', col_name))
data = ', '.join(f'"{column_name}": {column}' for column, column_name in column_list)
if ignore_index_value == True: # noqa
func_text.append(f'return pandas.DataFrame({{{data}}})\n')
else:
if indexes_comparable == False: # noqa
func_text.append(f'raise SDCLimitation("Indexes of dataframes are expected to have comparable '
f'(both Numeric or String) types if parameter ignore_index is set to False.")')
else:
func_text += [f'joined_index = hpat_arrays_append(df.index, other.index)\n',
f'return pandas.DataFrame({{{data}}}, index=joined_index)\n']
func_definition.extend([indent + func_line for func_line in func_text])
func_def = '\n'.join(func_definition)
global_vars = {'pandas': pandas,
'init_series': sdc.hiframes.api.init_series,
'fill_array': sdc.datatypes.common_functions.fill_array,
'fill_str_array': sdc.datatypes.common_functions.fill_str_array,
'hpat_arrays_append': sdc.datatypes.common_functions.hpat_arrays_append,
'SDCLimitation': SDCLimitation}
return func_def, global_vars
@sdc_overload_method(DataFrameType, 'append')
def sdc_pandas_dataframe_append(df, other, ignore_index=False, verify_integrity=False, sort=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.append
Limitations
-----------
- Parameters ``verify_integrity`` and ``sort`` are unsupported.
- Parameter ``other`` can be only :obj:`pandas.DataFrame`.
- Indexes of dataframes are expected to have comparable (both Numeric or String) types if parameter ignore_index
is set to False.
- This function may reveal slower performance than Pandas* on user system. Users should exercise a tradeoff
between staying in JIT-region with that function or going back to interpreter mode.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_append.py
:language: python
:lines: 37-
:caption: Appending rows of other to the end of caller, returning a new object. Columns in other that are not
in the caller are added as new columns.
:name: ex_dataframe_append
.. command-output:: python ./dataframe/dataframe_append.py
:cwd: ../../../examples
.. seealso::
`pandas.concat <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html>`_
General function to concatenate DataFrame or Series objects.
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.DataFrame.append` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_append*
"""
_func_name = 'append'
ty_checker = TypeChecker(f'Method {_func_name}().')
ty_checker.check(df, DataFrameType)
# TODO: support other array-like types
ty_checker.check(other, DataFrameType)
if not isinstance(verify_integrity, (bool, types.Boolean, types.Omitted)) and verify_integrity:
ty_checker.raise_exc(verify_integrity, 'boolean', 'verify_integrity')
if not isinstance(sort, (bool, types.Boolean, types.Omitted)) and sort is not None:
ty_checker.raise_exc(sort, 'boolean, None', 'sort')
if not isinstance(ignore_index, (bool, types.Boolean, types.Omitted)):
ty_checker.raise_exc(ignore_index, 'boolean', 'ignore_index')
none_or_numeric_indexes = ((isinstance(df.index, types.NoneType) or isinstance(df.index, types.Number)) and
(isinstance(other.index, types.NoneType) or isinstance(other.index, types.Number)))
indexes_comparable = check_types_comparable(df.index, other.index) or none_or_numeric_indexes
if isinstance(ignore_index, types.Literal):
ignore_index = ignore_index.literal_value
elif not (ignore_index is False or isinstance(ignore_index, types.Omitted)):
raise SDCLimitation("Parameter ignore_index should be Literal")
args = {'ignore_index': False, 'verify_integrity': False, 'sort': None}
def sdc_pandas_dataframe_append_impl(df, other, _func_name, ignore_index, indexes_comparable, args):
loc_vars = {}
func_def, global_vars = sdc_pandas_dataframe_append_codegen(df, other, _func_name, ignore_index,
indexes_comparable, args)
exec(func_def, global_vars, loc_vars)
_append_impl = loc_vars['sdc_pandas_dataframe_append_impl']
return _append_impl
return sdc_pandas_dataframe_append_impl(df, other, _func_name, ignore_index, indexes_comparable, args)
# Example func_text for func_name='count' columns=('A', 'B'):
#
# def _df_count_impl(df, axis=0, level=None, numeric_only=False):
# series_A = init_series(df._data[0])
# result_A = series_A.count(level=level)
# series_B = init_series(df._data[1])
# result_B = series_B.count(level=level)
# return pandas.Series([result_A, result_B], ['A', 'B'])
def _dataframe_reduce_columns_codegen(func_name, func_params, series_params, columns, column_loc):
result_name_list = []
joined = ', '.join(func_params)
func_lines = [f'def _df_{func_name}_impl({joined}):']
for i, c in enumerate(columns):
col_loc = column_loc[c]
type_id, col_id = col_loc.type_id, col_loc.col_id
result_c = f'result_{i}'
func_lines += [f' series_{i} = pandas.Series({func_params[0]}._data[{type_id}][{col_id}])',
f' {result_c} = series_{i}.{func_name}({series_params})']
result_name_list.append(result_c)
all_results = ', '.join(result_name_list)
all_columns = ', '.join([f"'{c}'" for c in columns])
func_lines += [f' return pandas.Series([{all_results}], [{all_columns}])']
func_text = '\n'.join(func_lines)
global_vars = {'pandas': pandas}
return func_text, global_vars
def sdc_pandas_dataframe_reduce_columns(df, func_name, params, ser_params):
all_params = ['df']
ser_par = []
for key, value in params.items():
all_params.append('{}={}'.format(key, value))
for key, value in ser_params.items():
ser_par.append('{}={}'.format(key, value))
s_par = '{}'.format(', '.join(ser_par[:]))
df_func_name = f'_df_{func_name}_impl'
func_text, global_vars = _dataframe_reduce_columns_codegen(func_name, all_params, s_par, df.columns,
df.column_loc)
loc_vars = {}
exec(func_text, global_vars, loc_vars)
_reduce_impl = loc_vars[df_func_name]
return _reduce_impl
def _dataframe_reduce_columns_codegen_head(func_name, func_params, series_params, columns, df):
"""
Example func_text for func_name='head' columns=('float', 'int', 'string'):
def _df_head_impl(df, n=5):
series_float = pandas.Series(df._data[0])
result_float = series_float.head(n=n)
series_int = pandas.Series(df._data[1])
result_int = series_int.head(n=n)
series_string = pandas.Series(df._data[2])
result_string = series_string.head(n=n)
return pandas.DataFrame({"float": result_float, "int": result_int, "string": result_string},
index = df._index[:n])
"""
results = []
joined = ', '.join(func_params)
func_lines = [f'def _df_{func_name}_impl(df, {joined}):']
ind = df_index_codegen_head(df)
for i, c in enumerate(columns):
result_c = f'result_{c}'
func_lines += [f' series_{c} = pandas.Series(df._data[{i}])',
f' {result_c} = series_{c}.{func_name}({series_params})']
results.append((columns[i], result_c))
data = ', '.join(f'"{col}": {data}' for col, data in results)
func_lines += [f' return pandas.DataFrame({{{data}}}, {ind})']
func_text = '\n'.join(func_lines)
global_vars = {'pandas': pandas}
return func_text, global_vars
def sdc_pandas_dataframe_head_codegen(df, func_name, params, ser_params):
all_params = kwsparams2list(params)
ser_par = kwsparams2list(ser_params)
s_par = ', '.join(ser_par)
df_func_name = f'_df_{func_name}_impl'
func_text, global_vars = _dataframe_reduce_columns_codegen_head(func_name, all_params, s_par, df.columns, df)
loc_vars = {}
exec(func_text, global_vars, loc_vars)
_reduce_impl = loc_vars[df_func_name]
return _reduce_impl
def df_index_codegen_head(self):
# TODO: Rewrite when DF constructor will be fixed with index=None
if isinstance(self.index, types.NoneType):
return ''
return 'index=df._index[:n]'
@sdc_overload_method(DataFrameType, 'head')
def head_overload(df, n=5):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.head
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_head.py
:language: python
:lines: 37-
:caption: Return the first n rows.
:name: ex_dataframe_head
.. command-output:: python ./dataframe/dataframe_head.py
:cwd: ../../../examples
.. seealso::
:ref:`DataFrame.tail <pandas.DataFrame.tail>`
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas Series method :meth:`pandas.Series.head` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_df_head*
"""
name = 'head'
if isinstance(n, types.Omitted):
n = n.value
params = {'n': 5}
ser_par = {'n': 'n'}
return sdc_pandas_dataframe_head_codegen(df, name, params, ser_par)
def _dataframe_codegen_copy(func_params, series_params, df):
"""
Example func_text for func_name='copy' columns=('A', 'B', 'C'):
def _df_copy_impl(df, deep=True):
series_0 = pandas.Series(df._data[0])
result_0 = series_0.copy(deep=deep)
series_1 = pandas.Series(df._data[1])
result_1 = series_1.copy(deep=deep)
return pandas.DataFrame({"A": result_0, "B": result_1}, index=df._index)
"""
results = []
series_params_str = ', '.join(kwsparams2list(series_params))
func_params_str = ', '.join(kwsparams2list(func_params))
func_lines = [f"def _df_copy_impl(df, {func_params_str}):"]
index = df_index_codegen_all(df)
for i, c in enumerate(df.columns):
result_c = f"result_{i}"
func_lines += [f" series_{i} = pandas.Series(df._data[{i}], name='{c}')",
f" {result_c} = series_{i}.copy({series_params_str})"]
results.append((c, result_c))
data = ', '.join(f'"{col}": {data}' for col, data in results)
func_lines += [f" return pandas.DataFrame({{{data}}}, {index})"]
func_text = '\n'.join(func_lines)
global_vars = {'pandas': pandas}
return func_text, global_vars
def sdc_pandas_dataframe_copy_codegen(df, params, series_params):
func_text, global_vars = _dataframe_codegen_copy(params, series_params, df)
loc_vars = {}
exec(func_text, global_vars, loc_vars)
_reduce_impl = loc_vars['_df_copy_impl']
return _reduce_impl
def df_index_codegen_all(self):
if isinstance(self.index, types.NoneType):
return ''
return 'index=df._index'
@sdc_overload_method(DataFrameType, 'copy')
def copy_overload(df, deep=True):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.copy
Limitations
-----------
- Parameter deep=False is currently unsupported for indexes by Intel Scalable Dataframe Compiler
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_copy.py
:language: python
:lines: 36-
:caption: Make a copy of this object’s indices and data.
:name: ex_dataframe_copy
.. command-output:: python ./dataframe/dataframe_copy.py
:cwd: ../../../examples
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.Series.copy` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_df_copy*
"""
ty_checker = TypeChecker("Method copy().")
ty_checker.check(df, DataFrameType)
if not (isinstance(deep, (types.Omitted, types.Boolean, types.NoneType)) or deep is True):
ty_checker.raise_exc(deep, 'boolean', 'deep')
params = {'deep': True}
series_params = {'deep': 'deep'}
return sdc_pandas_dataframe_copy_codegen(df, params, series_params)
def _dataframe_apply_columns_codegen(func_name, func_params, series_params, columns, column_loc):
result_name = []
joined = ', '.join(func_params)
func_lines = [f'def _df_{func_name}_impl({joined}):']
for i, c in enumerate(columns):
col_loc = column_loc[c]
type_id, col_id = col_loc.type_id, col_loc.col_id
result_c = f'result_{i}'
func_lines += [f' series_{i} = pandas.Series({func_params[0]}._data[{type_id}][{col_id}])',
f' {result_c} = series_{i}.{func_name}({series_params})']
result_name.append((result_c, c))
data = ', '.join(f'"{column_name}": {column}' for column, column_name in result_name)
func_lines += [f' return pandas.DataFrame({{{data}}})']
func_text = '\n'.join(func_lines)
global_vars = {'pandas': pandas}
return func_text, global_vars
def sdc_pandas_dataframe_apply_columns(df, func_name, params, ser_params):
all_params = ['df']
ser_par = []
for key, value in params.items():
all_params.append('{}={}'.format(key, value))
for key, value in ser_params.items():
ser_par.append('{}={}'.format(key, value))
s_par = ', '.join(ser_par)
df_func_name = f'_df_{func_name}_impl'
func_text, global_vars = _dataframe_apply_columns_codegen(func_name, all_params, s_par,
df.columns, df.column_loc)
loc_vars = {}
exec(func_text, global_vars, loc_vars)
_reduce_impl = loc_vars[df_func_name]
return _reduce_impl
def check_type(name, df, axis=None, skipna=None, level=None, numeric_only=None, ddof=1, min_count=0):
ty_checker = TypeChecker('Method {}().'.format(name))
ty_checker.check(df, DataFrameType)
if not (isinstance(axis, types.Omitted) or axis is None):
ty_checker.raise_exc(axis, 'unsupported', 'axis')
if not (isinstance(skipna, (types.Omitted, types.NoneType, types.Boolean)) or skipna is None):
ty_checker.raise_exc(skipna, 'bool', 'skipna')
if not (isinstance(level, types.Omitted) or level is None):
ty_checker.raise_exc(level, 'unsupported', 'level')
if not (isinstance(numeric_only, types.Omitted) or numeric_only is None):
ty_checker.raise_exc(numeric_only, 'unsupported', 'numeric_only')
if not (isinstance(ddof, (types.Omitted, types.Integer)) or ddof == 1):
ty_checker.raise_exc(ddof, 'int', 'ddof')
if not (isinstance(min_count, types.Omitted) or min_count == 0):
ty_checker.raise_exc(min_count, 'unsupported', 'min_count')
@sdc_overload_method(DataFrameType, 'median')
def median_overload(df, axis=None, skipna=None, level=None, numeric_only=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.median
Limitations
-----------
Parameters ``axis``, ``level`` and ``numeric_only`` are unsupported.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_median.py
:language: python
:lines: 35-
:caption: Return the median of the values for the columns.
:name: ex_dataframe_median
.. command-output:: python ./dataframe/dataframe_median.py
:cwd: ../../../examples
.. seealso::
:ref:`Series.median <pandas.Series.median>`
Returns the median of the values for the Series.
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.DataFrame.median` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_median*
"""
name = 'median'
check_type(name, df, axis=axis, skipna=skipna, level=level, numeric_only=numeric_only)
params = {'axis': None, 'skipna': None, 'level': None, 'numeric_only': None}
ser_par = {'skipna': 'skipna', 'level': 'level'}
return sdc_pandas_dataframe_reduce_columns(df, name, params, ser_par)
@sdc_overload_method(DataFrameType, 'mean')
def mean_overload(df, axis=None, skipna=None, level=None, numeric_only=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.mean
Limitations
-----------
Parameters ``axis``, ``level`` and ``numeric_only`` are unsupported.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_mean.py
:language: python
:lines: 35-
:caption: Return the mean of the values for the columns.
:name: ex_dataframe_mean
.. command-output:: python ./dataframe/dataframe_mean.py
:cwd: ../../../examples
.. seealso::
:ref:`Series.mean <pandas.Series.mean>`
Return the mean of the values for the Series.
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.DataFrame.mean` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_mean*
"""
name = 'mean'
check_type(name, df, axis=axis, skipna=skipna, level=level, numeric_only=numeric_only)
params = {'axis': None, 'skipna': None, 'level': None, 'numeric_only': None}
ser_par = {'skipna': 'skipna', 'level': 'level'}
return sdc_pandas_dataframe_reduce_columns(df, name, params, ser_par)
sdc_pandas_dataframe_rolling = sdc_overload_method(DataFrameType, 'rolling')(
gen_sdc_pandas_rolling_overload_body(_hpat_pandas_df_rolling_init, DataFrameType))
sdc_pandas_dataframe_rolling.__doc__ = sdc_pandas_rolling_docstring_tmpl.format(
ty='DataFrame', ty_lower='dataframe')
@sdc_overload_method(DataFrameType, 'std')
def std_overload(df, axis=None, skipna=None, level=None, ddof=1, numeric_only=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.std
Limitations
-----------
Parameters ``axis``, ``level`` and ``numeric_only`` are unsupported.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_std.py
:language: python
:lines: 35-
:caption: Return sample standard deviation over columns.
:name: ex_dataframe_std
.. command-output:: python ./dataframe/dataframe_std.py
:cwd: ../../../examples
.. seealso::
:ref:`Series.std <pandas.Series.std>`
Returns sample standard deviation over Series.
:ref:`Series.var <pandas.Series.var>`
Returns unbiased variance over Series.
:ref:`DataFrame.var <pandas.DataFrame.var>`
Returns unbiased variance over DataFrame.
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.DataFrame.std` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_std*
"""
name = 'std'
check_type(name, df, axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, ddof=ddof)
params = {'axis': None, 'skipna': None, 'level': None, 'ddof': 1, 'numeric_only': None}
ser_par = {'skipna': 'skipna', 'level': 'level', 'ddof': 'ddof'}
return sdc_pandas_dataframe_reduce_columns(df, name, params, ser_par)
@sdc_overload_method(DataFrameType, 'var')
def var_overload(df, axis=None, skipna=None, level=None, ddof=1, numeric_only=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.var
Limitations
-----------
Parameters ``axis``, ``level`` and ``numeric_only`` are unsupported.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_var.py
:language: python
:lines: 35-
:caption: Return unbiased variance over requested axis.
:name: ex_dataframe_var
.. command-output:: python ./dataframe/dataframe_var.py
:cwd: ../../../examples
.. seealso::
:ref:`Series.std <pandas.Series.std>`
Returns sample standard deviation over Series.
:ref:`Series.var<pandas.Series.var>`
Returns unbiased variance over Series.
:ref:`DataFrame.std <pandas.DataFrame.std>`
Returns sample standard deviation over DataFrame.
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.DataFrame.var` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_var*
"""
name = 'var'
check_type(name, df, axis=axis, skipna=skipna, level=level, numeric_only=numeric_only, ddof=ddof)
params = {'axis': None, 'skipna': None, 'level': None, 'ddof': 1, 'numeric_only': None}
ser_par = {'skipna': 'skipna', 'level': 'level', 'ddof': 'ddof'}
return sdc_pandas_dataframe_reduce_columns(df, name, params, ser_par)
@sdc_overload_method(DataFrameType, 'max')
def max_overload(df, axis=None, skipna=None, level=None, numeric_only=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.max
Limitations
-----------
Parameters ``axis``, ``level`` and ``numeric_only`` are unsupported.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_max.py
:language: python
:lines: 35-
:caption: Return the maximum of the values for the columns.
:name: ex_dataframe_max
.. command-output:: python ./dataframe/dataframe_max.py
:cwd: ../../../examples
.. seealso::
:ref:`Series.sum <pandas.Series.sum>`
Return the sum.
:ref:`Series.max <pandas.Series.max>`
Return the maximum.
:ref:`Series.idxmin <pandas.Series.idxmin>`
Return the index of the minimum.
:ref:`Series.idxmax <pandas.Series.idxmax>`
Return the index of the maximum.
:ref:`DataFrame.sum <pandas.DataFrame.sum>`
Return the sum over the requested axis.
:ref:`DataFrame.min <pandas.DataFrame.min>`
Return the minimum over the requested axis.
:ref:`DataFrame.idxmin <pandas.DataFrame.idxmin>`
Return the index of the minimum over the requested axis.
:ref:`DataFrame.idxmax <pandas.DataFrame.idxmax>`
Return the index of the maximum over the requested axis.
Intel Scalable Dataframe Compiler Developer Guide
*************************************************
Pandas DataFrame method :meth:`pandas.DataFrame.max` implementation.
.. only:: developer
Test: python -m sdc.runtests -k sdc.tests.test_dataframe.TestDataFrame.test_max*
"""
name = 'max'
check_type(name, df, axis=axis, skipna=skipna, level=level, numeric_only=numeric_only)
params = {'axis': None, 'skipna': None, 'level': None, 'numeric_only': None}
ser_par = {'skipna': 'skipna', 'level': 'level'}
return sdc_pandas_dataframe_reduce_columns(df, name, params, ser_par)
@sdc_overload_method(DataFrameType, 'min')
def min_overload(df, axis=None, skipna=None, level=None, numeric_only=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.min
Limitations
-----------
Parameters ``axis``, ``level`` and ``numeric_only`` are unsupported.
Examples
--------
.. literalinclude:: ../../../examples/dataframe/dataframe_min.py
:language: python
:lines: 35-
:caption: Return the minimum of the values for the columns.
:name: ex_dataframe_min
.. command-output:: python ./dataframe/dataframe_min.py
:cwd: ../../../examples
.. seealso::
:ref:`Series.sum <pandas.Series.sum>`
Return the sum.
:ref:`Series.min <pandas.Series.min>`
Return the minimum.
:ref:`Series.max <pandas.Series.max>`
Return the maximum.
:ref:`Series.idxmin <pandas.Series.idxmin>`
Return the index of the minimum.
:ref:`Series.idxmax <pandas.Series.idxmax>`
Return the index of the maximum.
:ref:`DataFrame.sum <pandas.DataFrame.sum>`
Return the sum over the requested axis.