maxframe 0.1.0b4__cp39-cp39-win32.whl → 1.0.0rc1__cp39-cp39-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of maxframe might be problematic. Click here for more details.

Files changed (81) hide show
  1. maxframe/__init__.py +1 -0
  2. maxframe/_utils.cp39-win32.pyd +0 -0
  3. maxframe/codegen.py +56 -3
  4. maxframe/config/config.py +15 -1
  5. maxframe/core/__init__.py +0 -3
  6. maxframe/core/entity/__init__.py +1 -8
  7. maxframe/core/entity/objects.py +3 -45
  8. maxframe/core/graph/core.cp39-win32.pyd +0 -0
  9. maxframe/core/graph/core.pyx +4 -4
  10. maxframe/dataframe/__init__.py +1 -0
  11. maxframe/dataframe/core.py +30 -8
  12. maxframe/dataframe/datasource/read_odps_query.py +3 -1
  13. maxframe/dataframe/datasource/read_odps_table.py +3 -1
  14. maxframe/dataframe/datastore/tests/__init__.py +13 -0
  15. maxframe/dataframe/datastore/tests/test_to_odps.py +48 -0
  16. maxframe/dataframe/datastore/to_odps.py +21 -0
  17. maxframe/dataframe/indexing/align.py +1 -1
  18. maxframe/dataframe/misc/__init__.py +4 -0
  19. maxframe/dataframe/misc/apply.py +3 -1
  20. maxframe/dataframe/misc/case_when.py +141 -0
  21. maxframe/dataframe/misc/memory_usage.py +2 -2
  22. maxframe/dataframe/misc/pivot_table.py +262 -0
  23. maxframe/dataframe/misc/tests/test_misc.py +84 -0
  24. maxframe/dataframe/plotting/core.py +2 -2
  25. maxframe/dataframe/reduction/core.py +2 -1
  26. maxframe/dataframe/statistics/corr.py +3 -3
  27. maxframe/dataframe/utils.py +7 -0
  28. maxframe/errors.py +13 -0
  29. maxframe/extension.py +12 -0
  30. maxframe/learn/contrib/utils.py +52 -0
  31. maxframe/learn/contrib/xgboost/__init__.py +26 -0
  32. maxframe/learn/contrib/xgboost/classifier.py +86 -0
  33. maxframe/learn/contrib/xgboost/core.py +156 -0
  34. maxframe/learn/contrib/xgboost/dmatrix.py +150 -0
  35. maxframe/learn/contrib/xgboost/predict.py +138 -0
  36. maxframe/learn/contrib/xgboost/regressor.py +78 -0
  37. maxframe/learn/contrib/xgboost/tests/__init__.py +13 -0
  38. maxframe/learn/contrib/xgboost/tests/test_core.py +43 -0
  39. maxframe/learn/contrib/xgboost/train.py +121 -0
  40. maxframe/learn/utils/__init__.py +15 -0
  41. maxframe/learn/utils/core.py +29 -0
  42. maxframe/lib/mmh3.cp39-win32.pyd +0 -0
  43. maxframe/lib/mmh3.pyi +43 -0
  44. maxframe/lib/wrapped_pickle.py +2 -1
  45. maxframe/odpsio/arrow.py +2 -3
  46. maxframe/odpsio/tableio.py +22 -0
  47. maxframe/odpsio/tests/test_schema.py +16 -11
  48. maxframe/opcodes.py +3 -0
  49. maxframe/protocol.py +108 -10
  50. maxframe/serialization/core.cp39-win32.pyd +0 -0
  51. maxframe/serialization/core.pxd +3 -0
  52. maxframe/serialization/core.pyi +64 -0
  53. maxframe/serialization/core.pyx +54 -25
  54. maxframe/serialization/exception.py +1 -1
  55. maxframe/serialization/pandas.py +7 -2
  56. maxframe/serialization/serializables/core.py +119 -12
  57. maxframe/serialization/serializables/tests/test_serializable.py +46 -4
  58. maxframe/session.py +28 -0
  59. maxframe/tensor/__init__.py +1 -1
  60. maxframe/tensor/arithmetic/tests/test_arithmetic.py +1 -1
  61. maxframe/tensor/base/__init__.py +2 -0
  62. maxframe/tensor/base/atleast_1d.py +74 -0
  63. maxframe/tensor/base/unique.py +205 -0
  64. maxframe/tensor/datasource/array.py +4 -2
  65. maxframe/tensor/datasource/scalar.py +1 -1
  66. maxframe/tensor/reduction/count_nonzero.py +1 -1
  67. maxframe/tests/test_protocol.py +34 -0
  68. maxframe/tests/test_utils.py +0 -12
  69. maxframe/tests/utils.py +2 -2
  70. maxframe/udf.py +63 -3
  71. maxframe/utils.py +22 -13
  72. {maxframe-0.1.0b4.dist-info → maxframe-1.0.0rc1.dist-info}/METADATA +3 -3
  73. {maxframe-0.1.0b4.dist-info → maxframe-1.0.0rc1.dist-info}/RECORD +80 -61
  74. maxframe_client/__init__.py +0 -1
  75. maxframe_client/fetcher.py +65 -3
  76. maxframe_client/session/odps.py +74 -5
  77. maxframe_client/session/task.py +65 -71
  78. maxframe_client/tests/test_session.py +64 -1
  79. maxframe_client/clients/spe.py +0 -104
  80. {maxframe-0.1.0b4.dist-info → maxframe-1.0.0rc1.dist-info}/WHEEL +0 -0
  81. {maxframe-0.1.0b4.dist-info → maxframe-1.0.0rc1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,141 @@
1
+ # Copyright 1999-2024 Alibaba Group Holding Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import numpy as np
16
+ from pandas.core.dtypes.cast import find_common_type
17
+
18
+ from ... import opcodes
19
+ from ...core import TILEABLE_TYPE
20
+ from ...serialization.serializables import FieldTypes, ListField
21
+ from ..core import SERIES_TYPE
22
+ from ..operators import DataFrameOperator, DataFrameOperatorMixin
23
+ from ..utils import apply_if_callable
24
+
25
+
26
+ class DataFrameCaseWhen(DataFrameOperator, DataFrameOperatorMixin):
27
+ _op_type_ = opcodes.CASE_WHEN
28
+
29
+ conditions = ListField("conditions", FieldTypes.reference, default=None)
30
+ replacements = ListField("replacements", FieldTypes.reference, default=None)
31
+
32
+ def __init__(self, output_types=None, **kw):
33
+ super().__init__(_output_types=output_types, **kw)
34
+
35
+ def _set_inputs(self, inputs):
36
+ super()._set_inputs(inputs)
37
+ it = iter(inputs)
38
+ next(it)
39
+ self.conditions = [
40
+ next(it) if isinstance(t, TILEABLE_TYPE) else t for t in self.conditions
41
+ ]
42
+ self.replacements = [
43
+ next(it) if isinstance(t, TILEABLE_TYPE) else t for t in self.replacements
44
+ ]
45
+
46
+ def __call__(self, series):
47
+ replacement_dtypes = [
48
+ it.dtype if isinstance(it, SERIES_TYPE) else np.array(it).dtype
49
+ for it in self.replacements
50
+ ]
51
+ dtype = find_common_type([series.dtype] + replacement_dtypes)
52
+
53
+ condition_tileables = [
54
+ it for it in self.conditions if isinstance(it, TILEABLE_TYPE)
55
+ ]
56
+ replacement_tileables = [
57
+ it for it in self.replacements if isinstance(it, TILEABLE_TYPE)
58
+ ]
59
+ inputs = [series] + condition_tileables + replacement_tileables
60
+
61
+ params = series.params
62
+ params["dtype"] = dtype
63
+ return self.new_series(inputs, **params)
64
+
65
+
66
+ def case_when(series, caselist):
67
+ """
68
+ Replace values where the conditions are True.
69
+
70
+ Parameters
71
+ ----------
72
+ caselist : A list of tuples of conditions and expected replacements
73
+ Takes the form: ``(condition0, replacement0)``,
74
+ ``(condition1, replacement1)``, ... .
75
+ ``condition`` should be a 1-D boolean array-like object
76
+ or a callable. If ``condition`` is a callable,
77
+ it is computed on the Series
78
+ and should return a boolean Series or array.
79
+ The callable must not change the input Series
80
+ (though pandas doesn`t check it). ``replacement`` should be a
81
+ 1-D array-like object, a scalar or a callable.
82
+ If ``replacement`` is a callable, it is computed on the Series
83
+ and should return a scalar or Series. The callable
84
+ must not change the input Series.
85
+
86
+ Returns
87
+ -------
88
+ Series
89
+
90
+ See Also
91
+ --------
92
+ Series.mask : Replace values where the condition is True.
93
+
94
+ Examples
95
+ --------
96
+ >>> import maxframe.dataframe as md
97
+ >>> c = md.Series([6, 7, 8, 9], name='c')
98
+ >>> a = md.Series([0, 0, 1, 2])
99
+ >>> b = md.Series([0, 3, 4, 5])
100
+
101
+ >>> c.case_when(caselist=[(a.gt(0), a), # condition, replacement
102
+ ... (b.gt(0), b)])
103
+ 0 6
104
+ 1 3
105
+ 2 1
106
+ 3 2
107
+ Name: c, dtype: int64
108
+ """
109
+ if not isinstance(caselist, list):
110
+ raise TypeError(
111
+ f"The caselist argument should be a list; instead got {type(caselist)}"
112
+ )
113
+
114
+ if not caselist:
115
+ raise ValueError(
116
+ "provide at least one boolean condition, "
117
+ "with a corresponding replacement."
118
+ )
119
+
120
+ for num, entry in enumerate(caselist):
121
+ if not isinstance(entry, tuple):
122
+ raise TypeError(
123
+ f"Argument {num} must be a tuple; instead got {type(entry)}."
124
+ )
125
+ if len(entry) != 2:
126
+ raise ValueError(
127
+ f"Argument {num} must have length 2; "
128
+ "a condition and replacement; "
129
+ f"instead got length {len(entry)}."
130
+ )
131
+ caselist = [
132
+ (
133
+ apply_if_callable(condition, series),
134
+ apply_if_callable(replacement, series),
135
+ )
136
+ for condition, replacement in caselist
137
+ ]
138
+ conditions = [case[0] for case in caselist]
139
+ replacements = [case[1] for case in caselist]
140
+ op = DataFrameCaseWhen(conditions=conditions, replacements=replacements)
141
+ return op(series)
@@ -58,7 +58,7 @@ class DataFrameMemoryUsage(DataFrameOperator, DataFrameOperatorMixin):
58
58
  """
59
59
  if df_or_series.ndim == 1:
60
60
  # the input data is a series, a Scalar will be returned
61
- return self.new_scalar([df_or_series], dtype=np.dtype(np.int_))
61
+ return self.new_scalar([df_or_series], dtype=np.dtype(int))
62
62
  else:
63
63
  # the input data is a DataFrame, a Scalar will be returned
64
64
  # calculate shape of returning series given ``op.index``
@@ -71,7 +71,7 @@ class DataFrameMemoryUsage(DataFrameOperator, DataFrameOperatorMixin):
71
71
  [df_or_series],
72
72
  index_value=self._adapt_index(df_or_series.columns_value),
73
73
  shape=new_shape,
74
- dtype=np.dtype(np.int_),
74
+ dtype=np.dtype(int),
75
75
  )
76
76
 
77
77
 
@@ -0,0 +1,262 @@
1
+ # Copyright 1999-2024 Alibaba Group Holding Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ from pandas.api.types import is_list_like
18
+
19
+ from ... import opcodes
20
+ from ...core import OutputType
21
+ from ...serialization.serializables import AnyField, BoolField, StringField
22
+ from ...utils import no_default
23
+ from ..operators import DataFrameOperator, DataFrameOperatorMixin
24
+ from ..utils import build_df, parse_index
25
+
26
+
27
+ class DataFramePivotTable(DataFrameOperator, DataFrameOperatorMixin):
28
+ _op_type_ = opcodes.PIVOT_TABLE
29
+
30
+ values = AnyField("values", default=None)
31
+ index = AnyField("index", default=None)
32
+ columns = AnyField("columns", default=None)
33
+ aggfunc = AnyField("aggfunc", default="mean")
34
+ fill_value = AnyField("fill_value", default=None)
35
+ margins = BoolField("margins", default=False)
36
+ dropna = BoolField("dropna", default=True)
37
+ margins_name = StringField("margins_name", default=None)
38
+ sort = BoolField("sort", default=False)
39
+
40
+ def __init__(self, **kw):
41
+ super().__init__(**kw)
42
+ self.output_types = [OutputType.dataframe]
43
+
44
+ def __call__(self, df):
45
+ index_value = columns_value = dtypes = None
46
+ if self.index is not None:
47
+ # index is now a required field
48
+ if len(self.index) == 1:
49
+ index_data = pd.Index(
50
+ [], dtype=df.dtypes[self.index[0]], name=self.index[0]
51
+ )
52
+ else:
53
+ index_data = pd.MultiIndex.from_frame(build_df(df[self.index]))
54
+ index_value = parse_index(index_data)
55
+
56
+ if self.columns is None: # output columns can be determined
57
+ sel_df = df
58
+ groupby_obj = sel_df.groupby(self.index)
59
+ if self.values:
60
+ groupby_obj = groupby_obj[self.values]
61
+ aggregated_df = groupby_obj.agg(self.aggfunc)
62
+ index_value = aggregated_df.index_value
63
+ columns_value = aggregated_df.columns_value
64
+ dtypes = aggregated_df.dtypes
65
+ else:
66
+ columns_value = dtypes = None
67
+ return self.new_dataframe(
68
+ [df],
69
+ shape=(np.nan, np.nan),
70
+ dtypes=dtypes,
71
+ columns_value=columns_value,
72
+ index_value=index_value,
73
+ )
74
+
75
+
76
+ def pivot_table(
77
+ data,
78
+ values=None,
79
+ index=None,
80
+ columns=None,
81
+ aggfunc="mean",
82
+ fill_value=None,
83
+ margins=False,
84
+ dropna=True,
85
+ margins_name="All",
86
+ sort=True,
87
+ ):
88
+ """
89
+ Create a spreadsheet-style pivot table as a DataFrame.
90
+
91
+ The levels in the pivot table will be stored in MultiIndex objects
92
+ (hierarchical indexes) on the index and columns of the result DataFrame.
93
+
94
+ Parameters
95
+ ----------
96
+ values : column to aggregate, optional
97
+ index : column, Grouper, array, or list of the previous
98
+ If an array is passed, it must be the same length as the data. The
99
+ list can contain any of the other types (except list).
100
+ Keys to group by on the pivot table index. If an array is passed,
101
+ it is being used as the same manner as column values.
102
+ columns : column, Grouper, array, or list of the previous
103
+ If an array is passed, it must be the same length as the data. The
104
+ list can contain any of the other types (except list).
105
+ Keys to group by on the pivot table column. If an array is passed,
106
+ it is being used as the same manner as column values.
107
+ aggfunc : function, list of functions, dict, default numpy.mean
108
+ If list of functions passed, the resulting pivot table will have
109
+ hierarchical columns whose top level are the function names
110
+ (inferred from the function objects themselves)
111
+ If dict is passed, the key is column to aggregate and value
112
+ is function or list of functions.
113
+ fill_value : scalar, default None
114
+ Value to replace missing values with (in the resulting pivot table,
115
+ after aggregation).
116
+ margins : bool, default False
117
+ Add all row / columns (e.g. for subtotal / grand totals).
118
+ dropna : bool, default True
119
+ Do not include columns whose entries are all NaN.
120
+ margins_name : str, default 'All'
121
+ Name of the row / column that will contain the totals
122
+ when margins is True.
123
+ sort : bool, default True
124
+ Specifies if the result should be sorted.
125
+
126
+ Returns
127
+ -------
128
+ DataFrame
129
+ An Excel style pivot table.
130
+
131
+ See Also
132
+ --------
133
+ DataFrame.pivot : Pivot without aggregation that can handle
134
+ non-numeric data.
135
+ DataFrame.melt: Unpivot a DataFrame from wide to long format,
136
+ optionally leaving identifiers set.
137
+ wide_to_long : Wide panel to long format. Less flexible but more
138
+ user-friendly than melt.
139
+
140
+ Examples
141
+ --------
142
+ >>> import numpy as np
143
+ >>> import maxframe.dataframe as md
144
+ >>> df = md.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
145
+ ... "bar", "bar", "bar", "bar"],
146
+ ... "B": ["one", "one", "one", "two", "two",
147
+ ... "one", "one", "two", "two"],
148
+ ... "C": ["small", "large", "large", "small",
149
+ ... "small", "large", "small", "small",
150
+ ... "large"],
151
+ ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
152
+ ... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
153
+ >>> df.execute()
154
+ A B C D E
155
+ 0 foo one small 1 2
156
+ 1 foo one large 2 4
157
+ 2 foo one large 2 5
158
+ 3 foo two small 3 5
159
+ 4 foo two small 3 6
160
+ 5 bar one large 4 6
161
+ 6 bar one small 5 8
162
+ 7 bar two small 6 9
163
+ 8 bar two large 7 9
164
+
165
+ This first example aggregates values by taking the sum.
166
+
167
+ >>> table = md.pivot_table(df, values='D', index=['A', 'B'],
168
+ ... columns=['C'], aggfunc=np.sum)
169
+ >>> table.execute()
170
+ C large small
171
+ A B
172
+ bar one 4.0 5.0
173
+ two 7.0 6.0
174
+ foo one 4.0 1.0
175
+ two NaN 6.0
176
+
177
+ We can also fill missing values using the `fill_value` parameter.
178
+
179
+ >>> table = md.pivot_table(df, values='D', index=['A', 'B'],
180
+ ... columns=['C'], aggfunc=np.sum, fill_value=0)
181
+ >>> table.execute()
182
+ C large small
183
+ A B
184
+ bar one 4 5
185
+ two 7 6
186
+ foo one 4 1
187
+ two 0 6
188
+
189
+ The next example aggregates by taking the mean across multiple columns.
190
+
191
+ >>> table = md.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
192
+ ... aggfunc={'D': np.mean,
193
+ ... 'E': np.mean})
194
+ >>> table.execute()
195
+ D E
196
+ A C
197
+ bar large 5.500000 7.500000
198
+ small 5.500000 8.500000
199
+ foo large 2.000000 4.500000
200
+ small 2.333333 4.333333
201
+
202
+ We can also calculate multiple types of aggregations for any given
203
+ value column.
204
+
205
+ >>> table = md.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
206
+ ... aggfunc={'D': np.mean,
207
+ ... 'E': [min, max, np.mean]})
208
+ >>> table.execute()
209
+ D E
210
+ mean max mean min
211
+ A C
212
+ bar large 5.500000 9.0 7.500000 6.0
213
+ small 5.500000 9.0 8.500000 8.0
214
+ foo large 2.000000 5.0 4.500000 4.0
215
+ small 2.333333 6.0 4.333333 2.0
216
+ """
217
+ if index is None and columns is None:
218
+ raise ValueError(
219
+ "No group keys passed, need to specify at least one of index or columns"
220
+ )
221
+
222
+ def make_col_list(col):
223
+ try:
224
+ if col in data.dtypes.index:
225
+ return [col]
226
+ except TypeError:
227
+ return col
228
+ return col
229
+
230
+ values_list = make_col_list(values)
231
+ index_list = make_col_list(index)
232
+ columns_list = make_col_list(columns)
233
+
234
+ name_to_attr = {"values": values_list, "index": index_list, "columns": columns_list}
235
+ for key, val in name_to_attr.items():
236
+ if val is None:
237
+ continue
238
+ if not is_list_like(val):
239
+ raise ValueError(f"Need to specify {key} as a list-like object.")
240
+ non_exist_key = next((c for c in val if c not in data.dtypes.index), no_default)
241
+ if non_exist_key is not no_default:
242
+ raise ValueError(
243
+ f"Column {non_exist_key} specified in {key} is not a valid column."
244
+ )
245
+
246
+ if columns is None and not margins:
247
+ if values_list:
248
+ data = data[index_list + values_list]
249
+ return data.groupby(index, sort=sort).agg(aggfunc)
250
+
251
+ op = DataFramePivotTable(
252
+ values=values,
253
+ index=index,
254
+ columns=columns,
255
+ aggfunc=aggfunc,
256
+ fill_value=fill_value,
257
+ margins=margins,
258
+ dropna=dropna,
259
+ margins_name=margins_name,
260
+ sort=sort,
261
+ )
262
+ return op(data)
@@ -18,9 +18,11 @@ import pytest
18
18
 
19
19
  from .... import opcodes
20
20
  from ....core import OutputType
21
+ from ....dataframe import DataFrame
21
22
  from ....tensor.core import TENSOR_TYPE
22
23
  from ... import eval as maxframe_eval
23
24
  from ... import get_dummies, to_numeric
25
+ from ...arithmetic import DataFrameGreater, DataFrameLess
24
26
  from ...core import CATEGORICAL_TYPE, DATAFRAME_TYPE, INDEX_TYPE, SERIES_TYPE
25
27
  from ...datasource.dataframe import from_pandas as from_pandas_df
26
28
  from ...datasource.index import from_pandas as from_pandas_index
@@ -405,3 +407,85 @@ def test_to_numeric():
405
407
 
406
408
  with pytest.raises(ValueError):
407
409
  _ = to_numeric([])
410
+
411
+
412
+ def test_case_when():
413
+ rs = np.random.RandomState(0)
414
+ raw = pd.DataFrame(
415
+ rs.randint(1000, size=(20, 8)), columns=["c" + str(i + 1) for i in range(8)]
416
+ )
417
+ df = from_pandas_df(raw, chunk_size=8)
418
+
419
+ with pytest.raises(TypeError):
420
+ df.c1.case_when(df.c2)
421
+ with pytest.raises(ValueError):
422
+ df.c1.case_when([])
423
+ with pytest.raises(TypeError):
424
+ df.c1.case_when([[]])
425
+ with pytest.raises(ValueError):
426
+ df.c1.case_when([()])
427
+
428
+ col = df.c1.case_when([(df.c2 < 10, 10), (df.c2 > 20, df.c3)])
429
+ assert len(col.inputs) == 4
430
+ assert isinstance(col.inputs[1].op, DataFrameLess)
431
+ assert isinstance(col.inputs[2].op, DataFrameGreater)
432
+
433
+
434
+ def test_apply():
435
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3], "c": [1, 2, 3]})
436
+
437
+ keys = [1, 2]
438
+
439
+ def f(x, keys):
440
+ if x["a"] in keys:
441
+ return [1, 0]
442
+ else:
443
+ return [0, 1]
444
+
445
+ apply_df = df[["a"]].apply(
446
+ f,
447
+ output_type="dataframe",
448
+ dtypes=pd.Series(["int64", "int64"]),
449
+ axis=1,
450
+ result_type="expand",
451
+ keys=keys,
452
+ )
453
+ assert apply_df.shape == (3, 2)
454
+
455
+
456
+ def test_pivot_table():
457
+ from ...groupby.aggregation import DataFrameGroupByAgg
458
+ from ...misc.pivot_table import DataFramePivotTable
459
+
460
+ raw = pd.DataFrame(
461
+ {
462
+ "A": "foo foo foo foo foo bar bar bar bar".split(),
463
+ "B": "one one one two two one one two two".split(),
464
+ "C": "small large large small small large small small large".split(),
465
+ "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
466
+ "E": [2, 4, 5, 5, 6, 6, 8, 9, 9],
467
+ }
468
+ )
469
+ df = from_pandas_df(raw, chunk_size=8)
470
+ with pytest.raises(ValueError):
471
+ df.pivot_table(index=123)
472
+ with pytest.raises(ValueError):
473
+ df.pivot_table(index=["F"])
474
+ with pytest.raises(ValueError):
475
+ df.pivot_table(values=["D", "E"], aggfunc="sum")
476
+
477
+ t = df.pivot_table(index="A")
478
+ assert isinstance(t.op, DataFrameGroupByAgg)
479
+ t = df.pivot_table(index="A", values=["D", "E"], aggfunc="sum")
480
+ assert isinstance(t.op, DataFrameGroupByAgg)
481
+
482
+ t = df.pivot_table(index=["A", "B"], values=["D", "E"], aggfunc="sum", margins=True)
483
+ assert isinstance(t.op, DataFramePivotTable)
484
+
485
+ t = df.pivot_table(index="A", columns=["B", "C"], aggfunc="sum")
486
+ assert isinstance(t.op, DataFramePivotTable)
487
+ assert t.shape == (np.nan, np.nan)
488
+
489
+ t = df.pivot_table(index=["A", "B"], columns="C", aggfunc="sum")
490
+ assert isinstance(t.op, DataFramePivotTable)
491
+ assert t.shape == (np.nan, np.nan)
@@ -17,7 +17,7 @@ from collections import OrderedDict
17
17
  import pandas as pd
18
18
 
19
19
  from ...core import ENTITY_TYPE, ExecutableTuple
20
- from ...utils import adapt_docstring
20
+ from ...utils import adapt_docstring, get_item_if_scalar
21
21
 
22
22
 
23
23
  class PlotAccessor:
@@ -34,7 +34,7 @@ class PlotAccessor:
34
34
  .fetch(session=session)
35
35
  )
36
36
  for p, v in zip(to_executes, executed):
37
- result[p] = v
37
+ result[p] = get_item_if_scalar(v)
38
38
 
39
39
  data = result.pop("__object__")
40
40
  pd_kwargs = kwargs.copy()
@@ -30,7 +30,7 @@ from ...serialization.serializables import (
30
30
  StringField,
31
31
  )
32
32
  from ...typing_ import TileableType
33
- from ...utils import pd_release_version, tokenize
33
+ from ...utils import get_item_if_scalar, pd_release_version, tokenize
34
34
  from ..operators import DATAFRAME_TYPE, DataFrameOperator, DataFrameOperatorMixin
35
35
  from ..utils import (
36
36
  build_df,
@@ -715,6 +715,7 @@ class ReductionCompiler:
715
715
  keys_to_vars = {inp.key: local_key_to_var[inp.key] for inp in t.inputs}
716
716
 
717
717
  def _interpret_var(v):
718
+ v = get_item_if_scalar(v)
718
719
  # get representation for variables
719
720
  if hasattr(v, "key"):
720
721
  return keys_to_vars[v.key]
@@ -43,7 +43,7 @@ class DataFrameCorr(DataFrameOperator, DataFrameOperatorMixin):
43
43
  def __call__(self, df_or_series):
44
44
  if isinstance(df_or_series, SERIES_TYPE):
45
45
  inputs = filter_inputs([df_or_series, self.other])
46
- return self.new_scalar(inputs, dtype=np.dtype(np.float_))
46
+ return self.new_scalar(inputs, dtype=np.dtype(float))
47
47
  else:
48
48
 
49
49
  def _filter_numeric(obj):
@@ -60,7 +60,7 @@ class DataFrameCorr(DataFrameOperator, DataFrameOperatorMixin):
60
60
  inputs = filter_inputs([df_or_series, self.other])
61
61
  if self.axis is None:
62
62
  dtypes = pd.Series(
63
- [np.dtype(np.float_)] * len(df_or_series.dtypes),
63
+ [np.dtype(float)] * len(df_or_series.dtypes),
64
64
  index=df_or_series.dtypes.index,
65
65
  )
66
66
  return self.new_dataframe(
@@ -85,7 +85,7 @@ class DataFrameCorr(DataFrameOperator, DataFrameOperatorMixin):
85
85
  return self.new_series(
86
86
  inputs,
87
87
  shape=shape,
88
- dtype=np.dtype(np.float_),
88
+ dtype=np.dtype(float),
89
89
  index_value=new_index_value,
90
90
  )
91
91
 
@@ -1136,6 +1136,13 @@ def concat_on_columns(objs: List) -> Any:
1136
1136
  return result
1137
1137
 
1138
1138
 
1139
+ def apply_if_callable(maybe_callable, obj, **kwargs):
1140
+ if callable(maybe_callable):
1141
+ return maybe_callable(obj, **kwargs)
1142
+
1143
+ return maybe_callable
1144
+
1145
+
1139
1146
  def patch_sa_engine_execute():
1140
1147
  """
1141
1148
  pandas did not resolve compatibility issue of sqlalchemy 2.0, the issue
maxframe/errors.py CHANGED
@@ -17,5 +17,18 @@ class MaxFrameError(Exception):
17
17
  pass
18
18
 
19
19
 
20
+ class MaxFrameIntentionalError(MaxFrameError):
21
+ pass
22
+
23
+
20
24
  class MaxFrameUserError(MaxFrameError):
21
25
  pass
26
+
27
+
28
+ class NoTaskServerResponseError(MaxFrameError):
29
+ pass
30
+
31
+
32
+ class SessionAlreadyClosedError(MaxFrameError):
33
+ def __init__(self, session_id: str):
34
+ super().__init__(f"Session {session_id} is already closed")
maxframe/extension.py CHANGED
@@ -48,6 +48,18 @@ class MaxFrameExtension(metaclass=abc.ABCMeta):
48
48
  """
49
49
  pass
50
50
 
51
+ @classmethod
52
+ async def reload_session(cls, session_id: str) -> None:
53
+ """
54
+ Reload the session state when the session is recovered from failover.
55
+
56
+ Parameters
57
+ ----------
58
+ session_id : str
59
+ The session id.
60
+ """
61
+ pass
62
+
51
63
  @classmethod
52
64
  def init_service_extension(cls) -> None:
53
65
  """
@@ -0,0 +1,52 @@
1
+ # Copyright 1999-2024 Alibaba Group Holding Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import sys
15
+
16
+
17
+ def make_import_error_func(package_name):
18
+ def _func(*_, **__): # pragma: no cover
19
+ raise ImportError(
20
+ f"Cannot import {package_name}, please reinstall that package."
21
+ )
22
+
23
+ return _func
24
+
25
+
26
+ def config_mod_getattr(mod_dict, globals_):
27
+ def __getattr__(name):
28
+ import importlib
29
+
30
+ if name in mod_dict:
31
+ mod_name, cls_name = mod_dict[name].rsplit(".", 1)
32
+ mod = importlib.import_module(mod_name, globals_["__name__"])
33
+ cls = globals_[name] = getattr(mod, cls_name)
34
+ return cls
35
+ else: # pragma: no cover
36
+ raise AttributeError(name)
37
+
38
+ if sys.version_info[:2] < (3, 7):
39
+ for _mod in mod_dict.keys():
40
+ __getattr__(_mod)
41
+
42
+ def __dir__():
43
+ return sorted([n for n in globals_ if not n.startswith("_")] + list(mod_dict))
44
+
45
+ globals_.update(
46
+ {
47
+ "__getattr__": __getattr__,
48
+ "__dir__": __dir__,
49
+ "__all__": list(__dir__()),
50
+ "__warningregistry__": dict(),
51
+ }
52
+ )