microdf-python 1.3.10__py3-none-any.whl → 1.4.1__py3-none-any.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.
microdf/_weights.py ADDED
@@ -0,0 +1,257 @@
1
+ """Pandas subclass hooks for copying weights and retaining row positions."""
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+
7
+ def weight_series(values, index):
8
+ """Own an independent float array aligned positionally to an index."""
9
+ return pd.Series(np.array(values, dtype=float, copy=True), index=index)
10
+
11
+
12
+ def aligned_weights(source, index):
13
+ """Align only when row identity can be established without guessing."""
14
+ if source.index.equals(index):
15
+ return weight_series(source.weights, index)
16
+ if source.index.is_unique:
17
+ positions = source.index.get_indexer(index)
18
+ if (positions >= 0).all():
19
+ return weight_series(source.weights.iloc[positions], index)
20
+ raise ValueError(
21
+ "Cannot propagate weights unambiguously to these rows. "
22
+ "Use positional selection, or explicitly supply weights for the result."
23
+ )
24
+
25
+
26
+ def finalize_weights(result, source, method, previous_weights):
27
+ """Propagate row weights after pandas has finalized its own metadata."""
28
+ if method == "transpose" and result.ndim == 2:
29
+ raise ValueError(
30
+ "Cannot transpose row weights onto columns. "
31
+ "Convert to a pandas DataFrame first and supply explicit result weights."
32
+ )
33
+ if method == "concat":
34
+ objects = source.objs
35
+ if not all(isinstance(obj, WeightPropagationMixin) for obj in objects):
36
+ raise ValueError(
37
+ "Cannot concatenate weighted and unweighted objects: "
38
+ "provide explicit weights for every input."
39
+ )
40
+ weights = concat_weights(result, objects, getattr(source, "axis", None))
41
+ result.weights = weights
42
+ if result.ndim == 2:
43
+ names = [obj.__dict__.get("weights_col") for obj in objects]
44
+ result.weights_col = (
45
+ names[0] if all(name == names[0] for name in names) else None
46
+ )
47
+ elif isinstance(source, WeightPropagationMixin):
48
+ if method == "reset_index" and source.ndim == result.ndim == 1:
49
+ # Series.reset_index(drop=True) changes labels, never row order.
50
+ # pandas 2 constructs a result; pandas 3 relabels a shallow copy.
51
+ result.weights = weight_series(source.weights, result.index)
52
+ elif method == "rename" and previous_weights is not None:
53
+ result.weights = weight_series(previous_weights, result.index)
54
+ else:
55
+ result.weights = aligned_weights(source, result.index)
56
+ return result
57
+
58
+
59
+ def concat_weights(result, objects, axis):
60
+ """Recover concat row identity without relying on pandas 2-only state."""
61
+ if objects[0].ndim == 1 and result.ndim == 2:
62
+ axis = 1
63
+ row_weights = None
64
+ if axis != 1 and len(result) == sum(len(obj) for obj in objects):
65
+ combined_index = objects[0].index.append([obj.index for obj in objects[1:]])
66
+ same_rows = result.index.equals(combined_index)
67
+ reset_rows = result.index.equals(pd.RangeIndex(len(result)))
68
+ keyed_rows = False
69
+ if (
70
+ isinstance(result.index, pd.MultiIndex)
71
+ and result.index.nlevels > combined_index.nlevels
72
+ ):
73
+ trailing = result.index.droplevel(
74
+ list(range(result.index.nlevels - combined_index.nlevels))
75
+ )
76
+ keyed_rows = trailing.equals(combined_index)
77
+ if same_rows or reset_rows or keyed_rows:
78
+ row_weights = np.concatenate([np.asarray(obj.weights) for obj in objects])
79
+ column_weights = None
80
+ if (
81
+ axis != 0
82
+ and result.ndim == 2
83
+ and len(result.columns)
84
+ == sum(obj.shape[1] if obj.ndim == 2 else 1 for obj in objects)
85
+ ):
86
+ values = np.empty(len(result))
87
+ known = np.zeros(len(result), dtype=bool)
88
+ conflict = False
89
+ for obj in objects:
90
+ if obj.index.equals(result.index):
91
+ positions = np.arange(len(result))
92
+ elif obj.index.is_unique:
93
+ positions = obj.index.get_indexer(result.index)
94
+ else:
95
+ conflict = True
96
+ break
97
+ present = positions >= 0
98
+ incoming = np.asarray(obj.weights)[positions[present]]
99
+ overlap = known[present]
100
+ if not np.array_equal(
101
+ values[present][overlap], incoming[overlap], equal_nan=True
102
+ ):
103
+ conflict = True
104
+ break
105
+ values[present] = incoming
106
+ known[present] = True
107
+ if not conflict and known.all():
108
+ column_weights = values
109
+ if row_weights is not None:
110
+ if column_weights is not None and not np.array_equal(
111
+ row_weights, column_weights, equal_nan=True
112
+ ):
113
+ raise ValueError(
114
+ "Ambiguous weights: pandas did not expose the concat axis."
115
+ )
116
+ return weight_series(row_weights, result.index)
117
+ if column_weights is not None:
118
+ return weight_series(column_weights, result.index)
119
+ raise ValueError(
120
+ "Cannot propagate concat weights: conflicting or ambiguous row weights."
121
+ )
122
+
123
+
124
+ class WeightPropagationMixin:
125
+ """Use positional provenance for pandas operations that select rows."""
126
+
127
+ def _plain(self):
128
+ return (
129
+ pd.Series(self, copy=False)
130
+ if self.ndim == 1
131
+ else pd.DataFrame(self, copy=False)
132
+ )
133
+
134
+ def _weighted_result(self, plain, weights):
135
+ result = type(self)(plain, weights=weight_series(weights, plain.index))
136
+ if self.ndim == 2:
137
+ result.weights_col = self.__dict__.get("weights_col")
138
+ return result
139
+
140
+ def _finish_row_operation(self, plain, positions, inplace=False):
141
+ result = self._weighted_result(plain, self.weights.iloc[positions])
142
+ if inplace:
143
+ self._update_inplace(result)
144
+ self.weights = result.weights
145
+ return None
146
+ return result
147
+
148
+ def take(self, indices, axis=0, **kwargs):
149
+ """Take values and weights using the same positional indexer."""
150
+ axis = self._get_axis_number(axis)
151
+ plain = self._plain().take(indices, axis=axis, **kwargs)
152
+ weights = self.weights.iloc[indices] if axis == 0 else self.weights
153
+ return self._weighted_result(plain, weights)
154
+
155
+ def _slice(self, slobj, axis=0):
156
+ plain = self._plain()._slice(slobj, axis=axis)
157
+ weights = self.weights.iloc[slobj] if axis == 0 else self.weights
158
+ return self._weighted_result(plain, weights)
159
+
160
+ def _reindex_with_indexers(
161
+ self, reindexers, fill_value=None, copy=False, allow_dups=False
162
+ ):
163
+ plain = self._plain()._reindex_with_indexers(
164
+ reindexers, fill_value=fill_value, allow_dups=allow_dups
165
+ )
166
+ if copy:
167
+ plain = plain.copy()
168
+ indexer = reindexers.get(0, (None, None))[1]
169
+ if indexer is not None:
170
+ if (np.asarray(indexer) < 0).any():
171
+ raise ValueError(
172
+ "Cannot invent weights for new rows introduced by reindex."
173
+ )
174
+ weights = self.weights.iloc[indexer]
175
+ else:
176
+ weights = self.weights
177
+ return self._weighted_result(plain, weights)
178
+
179
+ def drop(
180
+ self,
181
+ labels=None,
182
+ axis=0,
183
+ index=None,
184
+ columns=None,
185
+ level=None,
186
+ inplace=False,
187
+ errors="raise",
188
+ ):
189
+ plain = self._plain().drop(
190
+ labels=labels,
191
+ axis=axis,
192
+ index=index,
193
+ columns=columns,
194
+ level=level,
195
+ errors=errors,
196
+ )
197
+ positions = pd.Series(np.arange(len(self)), index=self.index)
198
+ row_labels = (
199
+ index
200
+ if index is not None
201
+ else labels
202
+ if self._get_axis_number(axis) == 0
203
+ else None
204
+ )
205
+ if row_labels is not None:
206
+ positions = positions.drop(row_labels, level=level, errors=errors)
207
+ return self._finish_row_operation(plain, np.asarray(positions), inplace)
208
+
209
+ def sample(self, *args, **kwargs):
210
+ """Sample weights with the selected rows, including replacements."""
211
+ result = super().sample(*args, **kwargs)
212
+ result.weights = weight_series(result.weights, result.index)
213
+ return result
214
+
215
+ def sort_values(self, *args, **kwargs):
216
+ """Sort rows and weights together even when labels are duplicated."""
217
+ inplace = kwargs.pop("inplace", False)
218
+ axis = self._get_axis_number(kwargs.get("axis", 0))
219
+ if self.ndim == 2:
220
+ plain = self._plain()
221
+ if axis == 1:
222
+ plain = plain.sort_values(*args, **kwargs)
223
+ return self._finish_row_operation(plain, np.arange(len(self)), inplace)
224
+ marker = object()
225
+ plain = plain.copy(deep=False)
226
+ plain[marker] = np.arange(len(self))
227
+ plain = plain.sort_values(*args, **kwargs)
228
+ positions = np.asarray(plain.pop(marker), dtype=int)
229
+ else:
230
+ values = self._plain()
231
+ positions = pd.Series(
232
+ np.arange(len(self)), index=self.index, name=self.name
233
+ )
234
+ key = kwargs.pop("key", None)
235
+ positions = positions.sort_values(
236
+ *args,
237
+ key=lambda unused: values if key is None else key(values),
238
+ **kwargs,
239
+ )
240
+ plain = values.iloc[np.asarray(positions)]
241
+ plain.index = positions.index
242
+ positions = np.asarray(positions, dtype=int)
243
+ return self._finish_row_operation(plain, positions, inplace)
244
+
245
+ def sort_index(self, *args, **kwargs):
246
+ """Sort the index while preserving positional weight provenance."""
247
+ inplace = kwargs.pop("inplace", False)
248
+ axis = self._get_axis_number(kwargs.get("axis", 0))
249
+ if axis == 1:
250
+ plain = self._plain().sort_index(*args, **kwargs)
251
+ return self._finish_row_operation(plain, np.arange(len(self)), inplace)
252
+ positions = pd.Series(np.arange(len(self)), index=self.index).sort_index(
253
+ *args, **kwargs
254
+ )
255
+ plain = self._plain().iloc[np.asarray(positions)]
256
+ plain.index = positions.index
257
+ return self._finish_row_operation(plain, np.asarray(positions), inplace)
microdf/microdataframe.py CHANGED
@@ -8,93 +8,17 @@ import numpy as np
8
8
  import pandas as pd
9
9
 
10
10
  from microdf.microseries import MicroSeries, MicroSeriesGroupBy
11
+ from microdf._weights import (
12
+ WeightPropagationMixin,
13
+ aligned_weights,
14
+ finalize_weights,
15
+ weight_series,
16
+ )
11
17
 
12
18
  logger = logging.getLogger(__name__)
13
19
 
14
20
 
15
- class _MicroLocIndexer:
16
- """Custom loc indexer that returns MicroDataFrame with proper weights."""
17
-
18
- def __init__(self, mdf: "MicroDataFrame"):
19
- self._mdf = mdf
20
- # Get the parent's loc indexer
21
- self._parent_loc = pd.DataFrame.loc.fget(mdf)
22
-
23
- def __getitem__(self, key):
24
- # Use the parent DataFrame's loc indexer
25
- result = self._parent_loc[key]
26
-
27
- if isinstance(result, pd.DataFrame):
28
- # Get the filtered weights based on the result's index
29
- new_weights = self._mdf.weights.reindex(result.index)
30
- return MicroDataFrame(result, weights=new_weights)
31
- elif isinstance(result, pd.Series):
32
- # Single row or column selected
33
- if result.name in self._mdf.columns:
34
- # Column was selected - return MicroSeries with all weights
35
- return MicroSeries(result, weights=self._mdf.weights)
36
- else:
37
- # Row was selected - return as-is (scalar values for each col)
38
- return result
39
- else:
40
- # Scalar value
41
- return result
42
-
43
- def __setitem__(self, key, value):
44
- self._parent_loc[key] = value
45
- self._mdf._link_all_weights()
46
-
47
- def __getattr__(self, name):
48
- """Delegate unknown attributes to the parent loc indexer."""
49
- return getattr(self._parent_loc, name)
50
-
51
-
52
- class _MicroILocIndexer:
53
- """Custom iloc indexer that returns MicroDataFrame with proper weights."""
54
-
55
- def __init__(self, mdf: "MicroDataFrame"):
56
- self._mdf = mdf
57
- # Get the parent's iloc indexer
58
- self._parent_iloc = pd.DataFrame.iloc.fget(mdf)
59
-
60
- def __getitem__(self, key):
61
- # Use the parent DataFrame's iloc indexer
62
- result = self._parent_iloc[key]
63
-
64
- if isinstance(result, pd.DataFrame):
65
- # Get the filtered weights based on the result's index
66
- new_weights = self._mdf.weights.iloc[
67
- self._mdf.index.get_indexer(result.index)
68
- ]
69
- new_weights = pd.Series(new_weights.values, index=result.index)
70
- return MicroDataFrame(result, weights=new_weights)
71
- elif isinstance(result, pd.Series):
72
- # Single row or column selected
73
- if isinstance(key, tuple) and len(key) == 2:
74
- # df.iloc[:, col_idx] - column selection
75
- row_key = key[0]
76
- if isinstance(row_key, slice) and row_key == slice(None):
77
- # All rows selected for a column
78
- return MicroSeries(result, weights=self._mdf.weights)
79
- # Check if this is a column (result index matches mdf index)
80
- if result.index.equals(self._mdf.index):
81
- return MicroSeries(result, weights=self._mdf.weights)
82
- # Row selection - return as-is
83
- return result
84
- else:
85
- # Scalar value
86
- return result
87
-
88
- def __setitem__(self, key, value):
89
- self._parent_iloc[key] = value
90
- self._mdf._link_all_weights()
91
-
92
- def __getattr__(self, name):
93
- """Delegate unknown attributes to the parent iloc indexer."""
94
- return getattr(self._parent_iloc, name)
95
-
96
-
97
- class MicroDataFrame(pd.DataFrame):
21
+ class MicroDataFrame(WeightPropagationMixin, pd.DataFrame):
98
22
  # Declare weight state as pandas metadata. pandas includes
99
23
  # _metadata attributes in the pickle state, so weights now survive
100
24
  # pickling, to_pickle/read_pickle and copy.deepcopy instead of
@@ -112,20 +36,54 @@ class MicroDataFrame(pd.DataFrame):
112
36
  :type weights: np.array
113
37
  """
114
38
  super().__init__(*args, **kwargs)
115
- self.weights = None
39
+ # pandas normalizes mixed-dimensional concat inputs through this
40
+ # constructor, either as a Series or a one-column mapping. Preserve
41
+ # that Series' row weights before concat loses the original input.
42
+ weight_source = args[0] if args else kwargs.get("data")
43
+ if isinstance(weight_source, dict) and len(weight_source) == 1:
44
+ weight_source = next(iter(weight_source.values()))
45
+ if weights is None and isinstance(weight_source, MicroSeries):
46
+ weights = aligned_weights(weight_source, self.index)
47
+ self.weights = weight_series(np.ones(len(self)), self.index)
48
+ self.weights_col = None
116
49
  self.set_weights(weights)
117
50
  self._link_all_weights()
118
51
  self.override_df_functions()
119
52
 
120
- def __finalize__(self, other, method=None, **kwargs) -> "MicroDataFrame":
121
- """Retain copied weights when pandas finalizes a renamed result."""
122
- copied_weights = getattr(self, "weights", None) if method == "rename" else None
53
+ @property
54
+ def _constructor(self):
55
+ return MicroDataFrame
56
+
57
+ # A row or a column-summary Series has no per-observation weights.
58
+ # _ixs wraps column selections using their unambiguous row provenance.
59
+ _constructor_sliced = pd.Series
60
+
61
+ def _ixs(self, i, axis=0):
62
+ result = pd.DataFrame(self, copy=False)._ixs(i, axis=axis)
63
+ if axis == 1:
64
+ return MicroSeries(result, weights=self.weights)
65
+ return result
66
+
67
+ def _get_item_cache(self, item):
68
+ # Weight arrays are independently mutable; cached column wrappers would
69
+ # retain stale copies after an in-place edit to frame.weights.
70
+ return self._ixs(self.columns.get_loc(item), axis=1)
71
+
72
+ def __finalize__(self, other, method=None, **kwargs):
73
+ previous = self.__dict__.get("weights")
123
74
  super().__finalize__(other, method=method, **kwargs)
124
- if copied_weights is not None:
125
- # rename already called copy(); metadata propagation must not
126
- # replace those weights with the source's mutable Series.
127
- self.weights = copied_weights
128
- return self
75
+ return finalize_weights(self, other, method, previous)
76
+
77
+ @wraps(pd.DataFrame.cov)
78
+ def cov(self, *args, **kwargs) -> pd.DataFrame:
79
+ # Column summaries have no observation weights, even if labels match.
80
+ result = pd.DataFrame(self, copy=False).cov(*args, **kwargs)
81
+ return result.__finalize__(self, method="cov")
82
+
83
+ @wraps(pd.DataFrame.corr)
84
+ def corr(self, *args, **kwargs) -> pd.DataFrame:
85
+ result = pd.DataFrame(self, copy=False).corr(*args, **kwargs)
86
+ return result.__finalize__(self, method="corr")
129
87
 
130
88
  def __setstate__(self, state) -> None:
131
89
  """Restore a pickled MicroDataFrame.
@@ -141,23 +99,6 @@ class MicroDataFrame(pd.DataFrame):
141
99
  self._link_all_weights()
142
100
  self.override_df_functions()
143
101
 
144
- @property
145
- def loc(self) -> _MicroLocIndexer:
146
- """Label-based indexer that preserves MicroDataFrame type and weights.
147
-
148
- :return: Custom loc indexer for MicroDataFrame
149
- """
150
- return _MicroLocIndexer(self)
151
-
152
- @property
153
- def iloc(self) -> _MicroILocIndexer:
154
- """Integer-based indexer that preserves MicroDataFrame type and
155
- weights.
156
-
157
- :return: Custom iloc indexer for MicroDataFrame
158
- """
159
- return _MicroILocIndexer(self)
160
-
161
102
  def override_df_functions(self) -> None:
162
103
  """Override DataFrame functions to work with weighted operations."""
163
104
  for name in MicroSeries.FUNCTIONS:
@@ -378,7 +319,7 @@ class MicroDataFrame(pd.DataFrame):
378
319
  pass
379
320
 
380
321
  def _link_all_weights(self) -> None:
381
- if self.weights is None:
322
+ if self.weights is None or len(self.weights) == 0:
382
323
  if len(self) > 0:
383
324
  self.set_weights(np.ones((len(self))))
384
325
  # In pandas 3.0+, columns are wrapped as MicroSeries on access via
@@ -472,33 +413,19 @@ class MicroDataFrame(pd.DataFrame):
472
413
  # that treats it as a Series (equals(), reindex() in __getitem__).
473
414
  self.set_weights(np.ones(len(self)))
474
415
 
475
- def __getitem__(
476
- self, key: Union[str, List]
477
- ) -> Union[MicroSeries, "MicroDataFrame"]:
478
- # Let pandas handle the initial slicing
479
- result = super().__getitem__(key)
480
-
481
- # If the result is a DataFrame, re-synchronize the weights
482
- if isinstance(result, pd.DataFrame):
483
- new_weights = self.weights.reindex(result.index)
484
- return MicroDataFrame(result, weights=new_weights)
485
-
486
- # If the result is a Series (single column), wrap as MicroSeries
487
- if isinstance(result, pd.Series):
488
- return MicroSeries(result, weights=self.weights)
489
-
490
- # Otherwise, the result is a scalar, so just return it
491
- return result
416
+ def __getitem__(self, key):
417
+ return super().__getitem__(key)
492
418
 
493
419
  def catch_series_relapse(self) -> None:
494
420
  # In pandas 3.0+, we don't need to track series class changes since
495
421
  # __getitem__ always wraps columns as MicroSeries on access.
496
422
  pass
497
423
 
498
- def __setattr__(self, key, value) -> None:
424
+ def __setattr__(self, key, value):
425
+ weights = self.__dict__.get("weights") if key == "index" else None
499
426
  super().__setattr__(key, value)
500
- # No need to call catch_series_relapse in pandas 3.0+ since we wrap
501
- # on access rather than store MicroSeries internally.
427
+ if weights is not None and len(weights) == len(self.index):
428
+ self.weights = weight_series(weights, self.index)
502
429
 
503
430
  def reset_index(
504
431
  self,
@@ -567,13 +494,7 @@ class MicroDataFrame(pd.DataFrame):
567
494
  return out
568
495
 
569
496
  def copy(self, deep: Optional[bool] = True) -> "MicroDataFrame":
570
- res = super().copy(deep)
571
- # super().copy() corrupts self's column types to plain Series.
572
- # Restore them in O(N) instead of O(N²) by calling
573
- # _link_all_weights once rather than per-column __setitem__.
574
- self._link_all_weights()
575
- res = MicroDataFrame(res, weights=self.weights.copy(deep))
576
- return res
497
+ return super().copy(deep)
577
498
 
578
499
  def drop(
579
500
  self,
@@ -605,55 +526,15 @@ class MicroDataFrame(pd.DataFrame):
605
526
  dropped.
606
527
  :return: MicroDataFrame or None if inplace=True.
607
528
  """
608
- row_drop = axis in (0, "index") or index is not None
609
- if inplace:
610
- # Snapshot the pre-drop weights keyed by the pre-drop index so
611
- # we can reindex to the surviving rows after the drop.
612
- pre_drop_weights = pd.Series(self.weights.values, index=self.index.copy())
613
- # Perform in-place drop on the parent DataFrame
614
- super().drop(
615
- labels=labels,
616
- axis=axis,
617
- index=index,
618
- columns=columns,
619
- level=level,
620
- inplace=True,
621
- errors=errors,
622
- )
623
- if row_drop:
624
- surviving = pre_drop_weights.reindex(self.index)
625
- self.weights = pd.Series(
626
- surviving.values, index=self.index, dtype=float
627
- )
628
- else:
629
- self.weights = pd.Series(
630
- pre_drop_weights.values, index=self.index, dtype=float
631
- )
632
- self._link_all_weights()
633
- return None
634
- else:
635
- res = super().drop(
636
- labels=labels,
637
- axis=axis,
638
- index=index,
639
- columns=columns,
640
- level=level,
641
- inplace=False,
642
- errors=errors,
643
- )
644
- if row_drop:
645
- # Row drop: keep only the weights for surviving rows,
646
- # in the order of the resulting DataFrame.
647
- pre_drop_weights = pd.Series(self.weights.values, index=self.index)
648
- new_weights = pre_drop_weights.reindex(res.index).values
649
- else:
650
- new_weights = self.weights.values
651
- out = MicroDataFrame(res, weights=new_weights)
652
- # Guard against the set_weights path building weights with a
653
- # default RangeIndex, which would misalign against res.index
654
- # and silently zero weighted aggregations.
655
- out.weights = pd.Series(new_weights, index=out.index, dtype=float)
656
- return out
529
+ return super().drop(
530
+ labels=labels,
531
+ axis=axis,
532
+ index=index,
533
+ columns=columns,
534
+ level=level,
535
+ inplace=inplace,
536
+ errors=errors,
537
+ )
657
538
 
658
539
  def merge(
659
540
  self,