Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/pandas/core/computation/align.py: 23%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

100 statements  

1""" 

2Core eval alignment algorithms. 

3""" 

4from __future__ import annotations 

5 

6from functools import ( 

7 partial, 

8 wraps, 

9) 

10from typing import ( 

11 TYPE_CHECKING, 

12 Callable, 

13) 

14import warnings 

15 

16import numpy as np 

17 

18from pandas.errors import PerformanceWarning 

19from pandas.util._exceptions import find_stack_level 

20 

21from pandas.core.dtypes.generic import ( 

22 ABCDataFrame, 

23 ABCSeries, 

24) 

25 

26from pandas.core.base import PandasObject 

27import pandas.core.common as com 

28from pandas.core.computation.common import result_type_many 

29 

30if TYPE_CHECKING: 

31 from collections.abc import Sequence 

32 

33 from pandas._typing import F 

34 

35 from pandas.core.generic import NDFrame 

36 from pandas.core.indexes.api import Index 

37 

38 

39def _align_core_single_unary_op( 

40 term, 

41) -> tuple[partial | type[NDFrame], dict[str, Index] | None]: 

42 typ: partial | type[NDFrame] 

43 axes: dict[str, Index] | None = None 

44 

45 if isinstance(term.value, np.ndarray): 

46 typ = partial(np.asanyarray, dtype=term.value.dtype) 

47 else: 

48 typ = type(term.value) 

49 if hasattr(term.value, "axes"): 

50 axes = _zip_axes_from_type(typ, term.value.axes) 

51 

52 return typ, axes 

53 

54 

55def _zip_axes_from_type( 

56 typ: type[NDFrame], new_axes: Sequence[Index] 

57) -> dict[str, Index]: 

58 return {name: new_axes[i] for i, name in enumerate(typ._AXIS_ORDERS)} 

59 

60 

61def _any_pandas_objects(terms) -> bool: 

62 """ 

63 Check a sequence of terms for instances of PandasObject. 

64 """ 

65 return any(isinstance(term.value, PandasObject) for term in terms) 

66 

67 

68def _filter_special_cases(f) -> Callable[[F], F]: 

69 @wraps(f) 

70 def wrapper(terms): 

71 # single unary operand 

72 if len(terms) == 1: 

73 return _align_core_single_unary_op(terms[0]) 

74 

75 term_values = (term.value for term in terms) 

76 

77 # we don't have any pandas objects 

78 if not _any_pandas_objects(terms): 

79 return result_type_many(*term_values), None 

80 

81 return f(terms) 

82 

83 return wrapper 

84 

85 

86@_filter_special_cases 

87def _align_core(terms): 

88 term_index = [i for i, term in enumerate(terms) if hasattr(term.value, "axes")] 

89 term_dims = [terms[i].value.ndim for i in term_index] 

90 

91 from pandas import Series 

92 

93 ndims = Series(dict(zip(term_index, term_dims))) 

94 

95 # initial axes are the axes of the largest-axis'd term 

96 biggest = terms[ndims.idxmax()].value 

97 typ = biggest._constructor 

98 axes = biggest.axes 

99 naxes = len(axes) 

100 gt_than_one_axis = naxes > 1 

101 

102 for value in (terms[i].value for i in term_index): 

103 is_series = isinstance(value, ABCSeries) 

104 is_series_and_gt_one_axis = is_series and gt_than_one_axis 

105 

106 for axis, items in enumerate(value.axes): 

107 if is_series_and_gt_one_axis: 

108 ax, itm = naxes - 1, value.index 

109 else: 

110 ax, itm = axis, items 

111 

112 if not axes[ax].is_(itm): 

113 axes[ax] = axes[ax].union(itm) 

114 

115 for i, ndim in ndims.items(): 

116 for axis, items in zip(range(ndim), axes): 

117 ti = terms[i].value 

118 

119 if hasattr(ti, "reindex"): 

120 transpose = isinstance(ti, ABCSeries) and naxes > 1 

121 reindexer = axes[naxes - 1] if transpose else items 

122 

123 term_axis_size = len(ti.axes[axis]) 

124 reindexer_size = len(reindexer) 

125 

126 ordm = np.log10(max(1, abs(reindexer_size - term_axis_size))) 

127 if ordm >= 1 and reindexer_size >= 10000: 

128 w = ( 

129 f"Alignment difference on axis {axis} is larger " 

130 f"than an order of magnitude on term {repr(terms[i].name)}, " 

131 f"by more than {ordm:.4g}; performance may suffer." 

132 ) 

133 warnings.warn( 

134 w, category=PerformanceWarning, stacklevel=find_stack_level() 

135 ) 

136 

137 obj = ti.reindex(reindexer, axis=axis, copy=False) 

138 terms[i].update(obj) 

139 

140 terms[i].update(terms[i].value.values) 

141 

142 return typ, _zip_axes_from_type(typ, axes) 

143 

144 

145def align_terms(terms): 

146 """ 

147 Align a set of terms. 

148 """ 

149 try: 

150 # flatten the parse tree (a nested list, really) 

151 terms = list(com.flatten(terms)) 

152 except TypeError: 

153 # can't iterate so it must just be a constant or single variable 

154 if isinstance(terms.value, (ABCSeries, ABCDataFrame)): 

155 typ = type(terms.value) 

156 return typ, _zip_axes_from_type(typ, terms.value.axes) 

157 return np.result_type(terms.type), None 

158 

159 # if all resolved variables are numeric scalars 

160 if all(term.is_scalar for term in terms): 

161 return result_type_many(*(term.value for term in terms)).type, None 

162 

163 # perform the main alignment 

164 typ, axes = _align_core(terms) 

165 return typ, axes 

166 

167 

168def reconstruct_object(typ, obj, axes, dtype): 

169 """ 

170 Reconstruct an object given its type, raw value, and possibly empty 

171 (None) axes. 

172 

173 Parameters 

174 ---------- 

175 typ : object 

176 A type 

177 obj : object 

178 The value to use in the type constructor 

179 axes : dict 

180 The axes to use to construct the resulting pandas object 

181 

182 Returns 

183 ------- 

184 ret : typ 

185 An object of type ``typ`` with the value `obj` and possible axes 

186 `axes`. 

187 """ 

188 try: 

189 typ = typ.type 

190 except AttributeError: 

191 pass 

192 

193 res_t = np.result_type(obj.dtype, dtype) 

194 

195 if not isinstance(typ, partial) and issubclass(typ, PandasObject): 

196 return typ(obj, dtype=res_t, **axes) 

197 

198 # special case for pathological things like ~True/~False 

199 if hasattr(res_t, "type") and typ == np.bool_ and res_t != np.bool_: 

200 ret_value = res_t.type(obj) 

201 else: 

202 ret_value = typ(obj).astype(res_t) 

203 # The condition is to distinguish 0-dim array (returned in case of 

204 # scalar) and 1 element array 

205 # e.g. np.array(0) and np.array([0]) 

206 if ( 

207 len(obj.shape) == 1 

208 and len(obj) == 1 

209 and not isinstance(ret_value, np.ndarray) 

210 ): 

211 ret_value = np.array([ret_value]).astype(res_t) 

212 

213 return ret_value