-
Notifications
You must be signed in to change notification settings - Fork 42
/
pint_array.py
1196 lines (1018 loc) · 38.7 KB
/
pint_array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import re
import warnings
from importlib.metadata import version
from typing import Any, Callable, Dict, Optional, Union, cast
import numpy as np
import pandas as pd
import pint
from pandas import DataFrame, Series, Index
from pandas.api.extensions import (
ExtensionArray,
ExtensionDtype,
ExtensionScalarOpsMixin,
register_dataframe_accessor,
register_extension_dtype,
register_series_accessor,
)
from pandas.api.indexers import check_array_indexer
from pandas.api.types import is_integer, is_list_like, is_object_dtype, is_string_dtype
from pandas.compat import set_function_name
from pandas.core import nanops # type: ignore
from pint import Quantity as _Quantity
from pint import Unit as _Unit
from pint import compat, errors
# Magic 'unit' flagging columns with no unit support, used in
# quantify/dequantify
NO_UNIT = "No Unit"
pandas_version = version("pandas")
pandas_version_info = tuple(
int(x) if x.isdigit() else x for x in pandas_version.split(".")
)
class PintType(ExtensionDtype):
"""
A Pint duck-typed class, suitable for holding a quantity (with unit specified) dtype.
"""
type = _Quantity
# kind = 'O'
# str = '|O08'
# base = np.dtype('O')
# num = 102
units: Optional[_Unit] = None # Filled in by `construct_from_..._string`
_metadata = ("units",)
_match = re.compile(r"(P|p)int\[(?P<units>.+)\]")
_cache = {} # type: ignore
ureg = pint.get_application_registry()
@property
def _is_numeric(self):
# type: () -> bool
return True
def __new__(cls, units=None):
"""
Parameters
----------
units : Pint units or string
"""
if isinstance(units, PintType):
return units
elif units is None:
# empty constructor for pickle compat
return object.__new__(cls)
if not isinstance(units, _Unit):
units = cls._parse_dtype_strict(units)
# ureg.unit returns a quantity with a magnitude of 1
# eg 1 mm. Initialising a quantity and taking its unit
# TODO: Seperate units from quantities in pint
# to simplify this bit
units = cls.ureg.Quantity(1, units).units
try:
# TODO: fix when Pint implements Callable typing
# TODO: wrap string into PintFormatStr class
return cls._cache["{:P}".format(units)] # type: ignore
except KeyError:
u = object.__new__(cls)
u.units = units
cls._cache["{:P}".format(units)] = u # type: ignore
return u
@classmethod
def _parse_dtype_strict(cls, units):
if isinstance(units, str):
if units.lower() == "pint[]":
units = "pint[dimensionless]"
if units.lower().startswith("pint["):
if not units[-1] == "]":
raise ValueError("could not construct PintType")
m = cls._match.search(units)
if m is not None:
units = m.group("units")
if units is not None:
return units
raise ValueError("could not construct PintType")
@classmethod
def construct_from_string(cls, string):
"""
Strict construction from a string, raise a TypeError if not
possible
"""
if not isinstance(string, str):
raise TypeError(
f"'construct_from_string' expects a string, got {type(string)}"
)
if isinstance(string, str) and (
string.startswith("pint[") or string.startswith("Pint[")
):
# do not parse string like U as pint[U]
# avoid tuple to be regarded as unit
try:
return cls(units=string)
except ValueError:
pass
raise TypeError(f"Cannot construct a 'PintType' from '{string}'")
@classmethod
def construct_from_quantity_string(cls, string):
"""
Strict construction from a string, raise a TypeError if not
possible
"""
if not isinstance(string, str):
raise TypeError(
f"'construct_from_quantity_string' expects a string, got {type(string)}"
)
quantity = cls.ureg.Quantity(string)
return cls(units=quantity.units)
# def __unicode__(self):
# return compat.text_type(self.name)
@property
def name(self):
return str("pint[{units}]".format(units=self.units))
@property
def na_value(self):
return self.ureg.Quantity(np.nan, self.units)
def __hash__(self):
# make myself hashable
return hash(str(self))
def __eq__(self, other):
try:
other = PintType(other)
except (ValueError, errors.UndefinedUnitError):
return False
return self.units == other.units
@classmethod
def is_dtype(cls, dtype):
"""
Return a boolean if we if the passed type is an actual dtype that we
can match (via string or type)
"""
if isinstance(dtype, str):
if dtype.startswith("pint[") or dtype.startswith("Pint["):
try:
if cls._parse_dtype_strict(dtype) is not None:
return True
else:
return False
except ValueError:
return False
else:
return False
return super(PintType, cls).is_dtype(dtype)
@classmethod
def construct_array_type(cls):
return PintArray
def __repr__(self):
"""
Return a string representation for this object.
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
py2/py3.
"""
return self.name
_NumpyEADtype = (
pd.core.dtypes.dtypes.PandasDtype # type: ignore
if pandas_version_info < (2, 1)
else pd.core.dtypes.dtypes.NumpyEADtype # type: ignore
)
dtypemap = {
int: pd.Int64Dtype(),
np.int64: pd.Int64Dtype(),
np.int32: pd.Int32Dtype(),
np.int16: pd.Int16Dtype(),
np.int8: pd.Int8Dtype(),
# np.float128: pd.Float128Dtype(),
float: pd.Float64Dtype(),
np.float64: pd.Float64Dtype(),
np.float32: pd.Float32Dtype(),
np.complex128: _NumpyEADtype("complex128"),
np.complex64: _NumpyEADtype("complex64"),
# np.float16: pd.Float16Dtype(),
}
dtypeunmap = {v: k for k, v in dtypemap.items()}
class PintArray(ExtensionArray, ExtensionScalarOpsMixin):
"""Implements a class to describe an array of physical quantities:
the product of an array of numerical values and a unit of measurement.
Parameters
----------
values : pint.Quantity or array-like
Array of physical quantity values to be created.
dtype : PintType, str, or pint.Unit
Units of the physical quantity to be created. (Default value = None)
When values is a pint.Quantity, passing None as the dtype will use
the units from the pint.Quantity.
copy: bool
Whether to copy the values.
Returns
-------
"""
_data: ExtensionArray = cast(ExtensionArray, np.array([]))
context_name = None
context_units = None
def __init__(self, values, dtype=None, copy=False):
if dtype is None:
if isinstance(values, _Quantity):
dtype = values.units
elif isinstance(values, PintArray):
dtype = values._dtype
if dtype is None:
raise NotImplementedError
if not isinstance(dtype, PintType):
dtype = PintType(dtype)
self._dtype = dtype
if isinstance(values, _Quantity):
values = values.to(dtype.units).magnitude
elif isinstance(values, PintArray):
values = values._data
if isinstance(values, np.ndarray):
dtype = values.dtype
if dtype in dtypemap:
dtype = dtypemap[dtype]
values = pd.array(values, copy=copy, dtype=dtype)
copy = False
elif not isinstance(values, pd.core.arrays.numeric.NumericArray):
values = pd.array(values, copy=copy)
if copy:
values = values.copy()
self._data = values
self._Q = self.dtype.ureg.Quantity
def __getstate__(self):
# we need to discard the cached _Q, which is not pickleable
ret = dict(self.__dict__)
ret.pop("_Q")
return ret
def __setstate__(self, dct):
self.__dict__.update(dct)
self._Q = self.dtype.ureg.Quantity
@property
def dtype(self):
# type: () -> ExtensionDtype
"""An instance of 'ExtensionDtype'."""
return self._dtype
def __len__(self):
# type: () -> int
"""Length of this array
Returns
-------
length : int
"""
return len(self._data)
def __getitem__(self, item):
# type (Any) -> Any
"""Select a subset of self.
Parameters
----------
item : int, slice, or ndarray
* int: The position in 'self' to get.
* slice: A slice object, where 'start', 'stop', and 'step' are
integers or None
* ndarray: A 1-d boolean NumPy ndarray the same length as 'self'
Returns
-------
item : scalar or PintArray
"""
if is_integer(item):
return self._Q(self._data[item], self.units)
item = check_array_indexer(self, item)
return self.__class__(self._data[item], self.dtype)
def __setitem__(self, key, value):
# need to not use `not value` on numpy arrays
if isinstance(value, (list, tuple)) and (not value):
# doing nothing here seems to be ok
return
if isinstance(value, _Quantity):
value = value.to(self.units).magnitude
elif is_list_like(value) and len(value) > 0:
if isinstance(value[0], _Quantity):
value = [item.to(self.units).magnitude for item in value]
if len(value) == 1:
value = value[0]
key = check_array_indexer(self, key)
# Filter out invalid values for our array type(s)
try:
self._data[key] = value
except IndexError as e:
msg = "Mask is wrong length. {}".format(e)
raise IndexError(msg)
def _formatter(self, boxed=False):
"""Formatting function for scalar values.
This is used in the default '__repr__'. The returned formatting
function receives scalar Quantities.
# type: (bool) -> Callable[[Any], Optional[str]]
Parameters
----------
boxed: bool, default False
An indicated for whether or not your array is being printed
within a Series, DataFrame, or Index (True), or just by
itself (False). This may be useful if you want scalar values
to appear differently within a Series versus on its own (e.g.
quoted or not).
Returns
-------
Callable[[Any], str]
A callable that gets instances of the scalar type and
returns a string. By default, :func:`repr` is used
when ``boxed=False`` and :func:`str` is used when
``boxed=True``.
"""
float_format = pint.formatting.remove_custom_flags(
self.dtype.ureg.default_format
)
def formatting_function(quantity):
if isinstance(quantity.magnitude, float):
return "{:{float_format}}".format(
quantity.magnitude, float_format=float_format
)
else:
return str(quantity.magnitude)
return formatting_function
def isna(self):
# type: () -> np.ndarray
"""Return a Boolean NumPy array indicating if each value is missing.
Returns
-------
missing : np.array
"""
return cast(np.ndarray, self._data.isna())
def astype(self, dtype, copy=True):
"""Cast to a NumPy array with 'dtype'.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
copy : bool, default True
Whether to copy the data, even if not necessary. If False,
a copy is made only if the old dtype does not match the
new dtype.
Returns
-------
array : ndarray
NumPy ndarray with 'dtype' for its dtype.
"""
if isinstance(dtype, str) and (
dtype.startswith("Pint[") or dtype.startswith("pint[")
):
dtype = PintType(dtype)
if isinstance(dtype, PintType):
if dtype == self._dtype and not copy:
return self
else:
return PintArray(self.quantity.to(dtype.units).magnitude, dtype)
# do *not* delegate to __array__ -> is required to return a numpy array,
# but somebody may be requesting another pandas array
# examples are e.g. PyArrow arrays as requested by "string[pyarrow]"
if is_object_dtype(dtype):
return self._to_array_of_quantity(copy=copy)
if is_string_dtype(dtype):
return pd.array([str(x) for x in self.quantity], dtype=dtype)
if isinstance(self._data, ExtensionArray):
return self._data.astype(dtype, copy=copy)
return pd.array(self.quantity.m, dtype, copy)
@property
def units(self):
return self._dtype.units
@property
def quantity(self):
return self._Q(self.numpy_data, self._dtype.units)
def take(self, indices, allow_fill=False, fill_value=None):
"""Take elements from an array.
# type: (Sequence[int], bool, Optional[Any]) -> PintArray
Parameters
----------
indices : sequence of integers
Indices to be taken.
allow_fill : bool, default False
How to handle negative values in `indices`.
* False: negative values in `indices` indicate positional indices
from the right (the default). This is similar to
:func:`numpy.take`.
* True: negative values in `indices` indicate
missing values. These values are set to `fill_value`. Any other
other negative values raise a ``ValueError``.
fill_value : any, optional
Fill value to use for NA-indices when `allow_fill` is True.
This may be ``None``, in which case the default NA value for
the type, ``self.dtype.na_value``, is used.
Returns
-------
PintArray
Raises
------
IndexError
When the indices are out of bounds for the array.
ValueError
When `indices` contains negative values other than ``-1``
and `allow_fill` is True.
Notes
-----
PintArray.take is called by ``Series.__getitem__``, ``.loc``,
``iloc``, when `indices` is a sequence of values. Additionally,
it's called by :meth:`Series.reindex`, or any other method
that causes realignemnt, with a `fill_value`.
See Also
--------
numpy.take
pandas.api.extensions.take
Examples
--------
"""
from pandas.core.algorithms import take
from pandas.api.types import is_scalar
data = self._data
if allow_fill and fill_value is None:
fill_value = self.dtype.na_value
if isinstance(fill_value, _Quantity):
fill_value = fill_value.to(self.units).magnitude
if not is_scalar(fill_value) and not fill_value.ndim:
# deal with Issue #165; for unit registries with force_ndarray_like = True,
# magnitude is in fact an array scalar, which will get rejected by pandas.
fill_value = fill_value[()]
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Turn off warning that PandasArray is deprecated for ``take``
result = take(data, indices, fill_value=fill_value, allow_fill=allow_fill)
return PintArray(result, dtype=self.dtype)
def copy(self, deep=False):
data = self._data
if deep:
data = copy.deepcopy(data)
else:
data = data.copy()
return type(self)(data, dtype=self.dtype)
@classmethod
def _concat_same_type(cls, to_concat):
output_units = to_concat[0].units
data = []
for a in to_concat:
converted_values = a.quantity.to(output_units).magnitude
data.append(np.atleast_1d(converted_values))
return cls(np.concatenate(data), output_units)
@classmethod
def _from_sequence(cls, scalars, dtype=None, copy=False):
"""
Initialises a PintArray from a list like of quantity scalars or a list like of floats and dtype
-----
Usage
PintArray._from_sequence([Q_(1,"m"),Q_(2,"m")])
"""
master_scalar = None
try:
master_scalar = next(i for i in scalars if hasattr(i, "units"))
except StopIteration:
if isinstance(scalars, PintArray):
dtype = scalars._dtype
if dtype is None:
raise ValueError(
"Cannot infer dtype. No dtype specified and empty array"
)
if dtype is None:
if not isinstance(master_scalar, _Quantity):
raise ValueError("No dtype specified and not a sequence of quantities")
dtype = PintType(master_scalar.units)
if isinstance(master_scalar, _Quantity):
scalars = [
(item.to(dtype.units).magnitude if hasattr(item, "to") else item)
for item in scalars
]
return cls(scalars, dtype=dtype, copy=copy)
@classmethod
def _from_sequence_of_strings(cls, scalars, dtype=None, copy=False):
if not dtype:
dtype = PintType.construct_from_quantity_string(scalars[0])
return cls._from_sequence([dtype.ureg.Quantity(x) for x in scalars])
@classmethod
def _from_factorized(cls, values, original):
from pandas.api.types import infer_dtype
if infer_dtype(values) != "object":
values = pd.array(values, copy=False)
return cls(values, dtype=original.dtype)
def _values_for_factorize(self):
# factorize can now handle differentiating various types of null values.
# These can only occur when the array has object dtype.
# However, for backwards compatibility we only use the null for the
# provided dtype. This may be revisited in the future, see GH#48476.
arr = self._data
if arr.dtype.kind == "O":
return np.array(arr, copy=False), self.dtype.na_value
return arr._values_for_factorize()
def value_counts(self, dropna=True):
"""
Returns a Series containing counts of each category.
Every category will have an entry, even those with a count of 0.
Parameters
----------
dropna : boolean, default True
Don't include counts of NaN.
Returns
-------
counts : Series
See Also
--------
Series.value_counts
"""
from pandas import Series
# compute counts on the data with no nans
data = self._data
nafilt = pd.isna(data)
na_value = pd.NA # NA value for index, not data, so not quantified
data = data[~nafilt]
index = list(set(data))
data_list = data.tolist()
array = [data_list.count(item) for item in index]
if not dropna:
index.append(na_value)
array.append(nafilt.sum())
return Series(np.asarray(array), index=index)
def unique(self):
"""Compute the PintArray of unique values.
Returns
-------
uniques : PintArray
"""
from pandas import unique
data = self._data
return self._from_sequence(unique(data), dtype=self.dtype)
def __contains__(self, item) -> Union[bool, np.bool_]:
if not isinstance(item, _Quantity):
return False
elif pd.isna(item.magnitude):
return cast(np.ndarray, self.isna()).any()
else:
return super().__contains__(item)
@property
def data(self):
return self._data
@property
def numpy_data(self):
data = self.data
if data.dtype in dtypeunmap:
try:
data = data.astype(dtypeunmap[data.dtype])
except Exception:
# We might get here for integer arrays with <NA> values
# In that case, the returned quantity will have dtype=O, which is less useful.
pass
if hasattr(data, "to_numpy"):
data = data.to_numpy()
return data
@property
def nbytes(self):
return self._data.nbytes
# The _can_hold_na attribute is set to True so that pandas internals
# will use the ExtensionDtype.na_value as the NA value in operations
# such as take(), reindex(), shift(), etc. In addition, those results
# will then be of the ExtensionArray subclass rather than an array
# of objects
_can_hold_na = True
@property
def _ndarray_values(self):
# type: () -> np.ndarray
"""Internal pandas method for lossy conversion to a NumPy ndarray.
This method is not part of the pandas interface.
The expectation is that this is cheap to compute, and is primarily
used for interacting with our indexers.
"""
return np.array(self)
@classmethod
def _create_method(cls, op, coerce_to_dtype=True):
"""
A class method that returns a method that will correspond to an
operator for an ExtensionArray subclass, by dispatching to the
relevant operator defined on the individual elements of the
ExtensionArray.
Parameters
----------
op : function
An operator that takes arguments op(a, b)
coerce_to_dtype : bool
boolean indicating whether to attempt to convert
the result to the underlying ExtensionArray dtype
(default True)
Returns
-------
A method that can be bound to a method of a class
Example
-------
Given an ExtensionArray subclass called MyExtensionArray, use
>>> __add__ = cls._create_method(operator.add)
in the class definition of MyExtensionArray to create the operator
for addition, that will be based on the operator implementation
of the underlying elements of the ExtensionArray
"""
def _binop(self, other):
def validate_length(obj1, obj2):
# validates length
# CHANGED: do not convert to listlike (why should we? pint.Quantity is perfecty able to handle that...)
try:
if len(obj1) != len(obj2):
raise ValueError("Lengths must match")
except TypeError:
pass
def convert_values(param):
# convert to a quantity or listlike
if isinstance(param, cls):
return param.quantity
elif isinstance(param, (_Quantity, _Unit)):
return param
elif (
is_list_like(param)
and len(param) > 0
and isinstance(param[0], _Quantity)
):
units = param[0].units
return type(param[0])([p.m_as(units) for p in param], units)
else:
return param
if isinstance(other, (Series, DataFrame, Index)):
return NotImplemented
lvalues = self.quantity
validate_length(lvalues, other)
rvalues = convert_values(other)
# If the operator is not defined for the underlying objects,
# a TypeError should be raised
res = op(lvalues, rvalues)
if op.__name__ == "divmod":
return (
cls.from_1darray_quantity(res[0]),
cls.from_1darray_quantity(res[1]),
)
if coerce_to_dtype:
try:
res = cls.from_1darray_quantity(res)
except TypeError:
pass
return res
op_name = f"__{op}__"
return set_function_name(_binop, op_name, cls)
@classmethod
def _create_arithmetic_method(cls, op):
return cls._create_method(op)
@classmethod
def _create_comparison_method(cls, op):
return cls._create_method(op, coerce_to_dtype=False)
@classmethod
def from_1darray_quantity(cls, quantity):
if not is_list_like(quantity.magnitude):
raise TypeError("quantity's magnitude is not list like")
return cls(quantity.magnitude, quantity.units)
def __array__(self, dtype=None, copy=False):
if dtype is None or is_object_dtype(dtype):
return self._to_array_of_quantity(copy=copy)
if is_string_dtype(dtype):
return np.array([str(x) for x in self.quantity], dtype=str)
return np.array(self._data, dtype=dtype, copy=copy)
def _to_array_of_quantity(self, copy=False):
qtys = [
self._Q(item, self._dtype.units)
if not pd.isna(item)
else self.dtype.na_value
for item in self._data
]
with warnings.catch_warnings(record=True):
return np.array(qtys, dtype="object", copy=copy)
def searchsorted(self, value, side="left", sorter=None):
"""
Find indices where elements should be inserted to maintain order.
.. versionadded:: 0.24.0
Find the indices into a sorted array `self` (a) such that, if the
corresponding elements in `v` were inserted before the indices, the
order of `self` would be preserved.
Assuming that `a` is sorted:
====== ============================
`side` returned index `i` satisfies
====== ============================
left ``self[i-1] < v <= self[i]``
right ``self[i-1] <= v < self[i]``
====== ============================
Parameters
----------
value : array_like
Values to insert into `self`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
sorter : 1-D array_like, optional
Optional array of integer indices that sort array a into ascending
order. They are typically the result of argsort.
Returns
-------
indices : array of ints
Array of insertion points with the same shape as `value`.
See Also
--------
numpy.searchsorted : Similar method from NumPy.
"""
# Note: the base tests provided by pandas only test the basics.
# We do not test
# 1. Values outside the range of the `data_for_sorting` fixture
# 2. Values between the values in the `data_for_sorting` fixture
# 3. Missing values.
arr = self._data
if isinstance(value, _Quantity):
value = value.to(self.units).magnitude
elif is_list_like(value) and len(value) > 0 and isinstance(value[0], _Quantity):
value = [item.to(self.units).magnitude for item in value]
return arr.searchsorted(value, side=side, sorter=sorter)
def map(self, mapper, na_action=None):
"""
Map values using an input mapping or function.
Parameters
----------
mapper : function, dict, or Series
Mapping correspondence.
na_action : {None, 'ignore'}, default None
If 'ignore', propagate NA values, without passing them to the
mapping correspondence. If 'ignore' is not supported, a
``NotImplementedError`` should be raised.
Returns
-------
If mapper is a function, operate on the magnitudes of the array and
"""
if pandas_version_info < (2, 1):
ser = pd.Series(self._to_array_of_quantity())
arr = ser.map(mapper, na_action).values
else:
from pandas.core.algorithms import map_array
arr = map_array(self, mapper, na_action)
master_scalar = None
try:
master_scalar = next(i for i in arr if hasattr(i, "units"))
except StopIteration:
# JSON mapper formatting Qs as str don't create PintArrays
# ...and that's OK. Caller will get array of values
return arr
return PintArray._from_sequence(arr, PintType(master_scalar.units))
def _reduce(self, name, *, skipna: bool = True, keepdims: bool = False, **kwds):
"""
Return a scalar result of performing the reduction operation.
Parameters
----------
name : str
Name of the function, supported values are:
{ any, all, min, max, sum, mean, median, prod,
std, var, sem, kurt, skew }.
skipna : bool, default True
If True, skip NaN values.
**kwargs
Additional keyword arguments passed to the reduction function.
Currently, `ddof` is the only supported kwarg.
Returns
-------
scalar
Raises
------
TypeError : subclass does not define reductions
"""
functions = {
"any": nanops.nanany,
"all": nanops.nanall,
"min": nanops.nanmin,
"max": nanops.nanmax,
"sum": nanops.nansum,
"mean": nanops.nanmean,
"median": nanops.nanmedian,
"std": nanops.nanstd,
"var": nanops.nanvar,
"sem": nanops.nansem,
"kurt": nanops.nankurt,
"skew": nanops.nanskew,
}
if name not in functions:
raise TypeError(f"cannot perform {name} with type {self.dtype}")
if isinstance(self._data, ExtensionArray):
try:
# TODO: https://github.com/pandas-dev/pandas-stubs/issues/850
result = self._data._reduce( # type: ignore
name, skipna=skipna, keepdims=keepdims, **kwds
)
except NotImplementedError:
result = cast(_Quantity, functions[name](self.numpy_data, **kwds))
if name in {"all", "any", "kurt", "skew"}:
return result
if name == "var":
if keepdims:
return PintArray(result, f"pint[({self.units})**2]")
return self._Q(result, self.units**2)
if keepdims:
return PintArray(result, self.dtype)
return self._Q(result, self.units)
def _accumulate(self, name: str, *, skipna: bool = True, **kwds):
if name == "cumprod":
raise TypeError("cumprod not supported for pint arrays")
functions: Dict[
str, Callable[[np._typing._SupportsArray[np.dtype[Any]]], Any]
] = {
"cummin": np.minimum.accumulate,
"cummax": np.maximum.accumulate,
"cumsum": np.cumsum,
}
if isinstance(self._data, ExtensionArray):
try:
# TODO: https://github.com/pandas-dev/pandas-stubs/issues/850
result = self._data._accumulate(name, **kwds) # type: ignore
except NotImplementedError:
result = functions[name](self.numpy_data, **kwds)
return self._from_sequence(result, self.units)
PintArray._add_arithmetic_ops()
PintArray._add_comparison_ops()
register_extension_dtype(PintType)
@register_dataframe_accessor("pint")
class PintDataFrameAccessor(object):
def __init__(self, pandas_obj):
self._obj = pandas_obj
def quantify(self, level=-1):
df = self._obj
df_columns = df.columns.to_frame()
unit_col_name = df_columns.columns[level]
units = df_columns[unit_col_name]
df_columns = df_columns.drop(columns=unit_col_name)
df_new = DataFrame(
{
i: PintArray(df.iloc[:, i], unit)
if unit != NO_UNIT
else df.values[:, i]
for i, unit in enumerate(units.values)
}
)
df_new.columns = df_columns.index.droplevel(unit_col_name)
df_new.index = df.index
return df_new
def dequantify(self):
def formatter_func(dtype):
formatter = "{:" + dtype.ureg.default_format + "}"
return formatter.format(dtype.units)
df = self._obj
df_columns = df.columns.to_frame()
df_columns["units"] = [
formatter_func(df.dtypes.iloc[i])
if isinstance(df.dtypes.iloc[i], PintType)
else NO_UNIT
for i, col in enumerate(df.columns)
]
data_for_df = []
for i, col in enumerate(df.columns):
if isinstance(df.dtypes.iloc[i], PintType):
data_for_df.append(