1
1
"""
2
2
Base and utility classes for pandas objects.
3
3
"""
4
+
4
5
import builtins
5
6
import textwrap
6
7
from typing import Dict , FrozenSet , List , Optional , Union
45
46
46
47
47
48
class PandasObject (DirNamesMixin ):
48
- """baseclass for various pandas objects"""
49
+ """
50
+ Baseclass for various pandas objects.
51
+ """
49
52
50
53
@property
51
54
def _constructor (self ):
52
- """class constructor (for this class it's just `__class__`"""
55
+ """
56
+ Class constructor (for this class it's just `__class__`.
57
+ """
53
58
return type (self )
54
59
55
60
def __repr__ (self ) -> str :
@@ -77,16 +82,14 @@ def __sizeof__(self):
77
82
"""
78
83
if hasattr (self , "memory_usage" ):
79
84
mem = self .memory_usage (deep = True )
80
- if not is_scalar (mem ):
81
- mem = mem .sum ()
82
- return int (mem )
85
+ return int (mem if is_scalar (mem ) else mem .sum ())
83
86
84
- # no memory_usage attribute, so fall back to
85
- # object's 'sizeof'
87
+ # no memory_usage attribute, so fall back to object's 'sizeof'
86
88
return super ().__sizeof__ ()
87
89
88
90
def _ensure_type (self : T , obj ) -> T :
89
- """Ensure that an object has same type as self.
91
+ """
92
+ Ensure that an object has same type as self.
90
93
91
94
Used by type checkers.
92
95
"""
@@ -95,7 +98,8 @@ def _ensure_type(self: T, obj) -> T:
95
98
96
99
97
100
class NoNewAttributesMixin :
98
- """Mixin which prevents adding new attributes.
101
+ """
102
+ Mixin which prevents adding new attributes.
99
103
100
104
Prevents additional attributes via xxx.attribute = "something" after a
101
105
call to `self.__freeze()`. Mainly used to prevent the user from using
@@ -106,7 +110,9 @@ class NoNewAttributesMixin:
106
110
"""
107
111
108
112
def _freeze (self ):
109
- """Prevents setting additional attributes"""
113
+ """
114
+ Prevents setting additional attributes.
115
+ """
110
116
object .__setattr__ (self , "__frozen" , True )
111
117
112
118
# prevent adding any attribute via s.xxx.new_attribute = ...
@@ -180,14 +186,12 @@ class SelectionMixin:
180
186
@property
181
187
def _selection_name (self ):
182
188
"""
183
- return a name for myself; this would ideally be called
184
- the 'name' property, but we cannot conflict with the
185
- Series.name property which can be set
189
+ Return a name for myself;
190
+
191
+ This would ideally be called the 'name' property,
192
+ but we cannot conflict with the Series.name property which can be set.
186
193
"""
187
- if self ._selection is None :
188
- return None # 'result'
189
- else :
190
- return self ._selection
194
+ return self ._selection
191
195
192
196
@property
193
197
def _selection_list (self ):
@@ -199,7 +203,6 @@ def _selection_list(self):
199
203
200
204
@cache_readonly
201
205
def _selected_obj (self ):
202
-
203
206
if self ._selection is None or isinstance (self .obj , ABCSeries ):
204
207
return self .obj
205
208
else :
@@ -246,12 +249,11 @@ def _gotitem(self, key, ndim: int, subset=None):
246
249
247
250
Parameters
248
251
----------
249
- key : string / list of selections
252
+ key : str / list of selections
250
253
ndim : 1,2
251
254
requested ndim of result
252
255
subset : object, default None
253
256
subset to act on
254
-
255
257
"""
256
258
raise AbstractMethodError (self )
257
259
@@ -266,7 +268,6 @@ def _try_aggregate_string_function(self, arg: str, *args, **kwargs):
266
268
- try to find a function (or attribute) on ourselves
267
269
- try to find a numpy function
268
270
- raise
269
-
270
271
"""
271
272
assert isinstance (arg , str )
272
273
@@ -585,7 +586,6 @@ def _shallow_copy(self, obj, **kwargs):
585
586
"""
586
587
return a new object with the replacement attributes
587
588
"""
588
-
589
589
if isinstance (obj , self ._constructor ):
590
590
obj = obj .obj
591
591
for attr in self ._attributes :
@@ -669,8 +669,7 @@ def item(self):
669
669
670
670
if len (self ) == 1 :
671
671
return next (iter (self ))
672
- else :
673
- raise ValueError ("can only convert an array of size 1 to a Python scalar" )
672
+ raise ValueError ("can only convert an array of size 1 to a Python scalar" )
674
673
675
674
@property
676
675
def nbytes (self ) -> int :
@@ -735,7 +734,6 @@ def array(self) -> ExtensionArray:
735
734
736
735
Examples
737
736
--------
738
-
739
737
For regular NumPy types like int, and float, a PandasArray
740
738
is returned.
741
739
@@ -851,12 +849,11 @@ def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs):
851
849
"""
852
850
if is_extension_array_dtype (self .dtype ):
853
851
return self .array .to_numpy (dtype , copy = copy , na_value = na_value , ** kwargs )
854
- else :
855
- if kwargs :
856
- msg = "to_numpy() got an unexpected keyword argument '{}'" .format (
857
- list (kwargs .keys ())[0 ]
858
- )
859
- raise TypeError (msg )
852
+ elif kwargs :
853
+ bad_keys = list (kwargs .keys ())[0 ]
854
+ raise TypeError (
855
+ f"to_numpy() got an unexpected keyword argument '{ bad_keys } '"
856
+ )
860
857
861
858
result = np .asarray (self ._values , dtype = dtype )
862
859
# TODO(GH-24345): Avoid potential double copy
@@ -1076,7 +1073,9 @@ def _reduce(
1076
1073
filter_type = None ,
1077
1074
** kwds ,
1078
1075
):
1079
- """ perform the reduction type operation if we can """
1076
+ """
1077
+ Perform the reduction type operation if we can.
1078
+ """
1080
1079
func = getattr (self , name , None )
1081
1080
if func is None :
1082
1081
raise TypeError (
@@ -1103,9 +1102,7 @@ def _map_values(self, mapper, na_action=None):
1103
1102
The output of the mapping function applied to the index.
1104
1103
If the function returns a tuple with more than one element
1105
1104
a MultiIndex will be returned.
1106
-
1107
1105
"""
1108
-
1109
1106
# we can fastpath dict/Series to an efficient map
1110
1107
# as we know that we are not going to have to yield
1111
1108
# python types
@@ -1341,7 +1338,9 @@ def is_monotonic(self) -> bool:
1341
1338
1342
1339
@property
1343
1340
def is_monotonic_increasing (self ) -> bool :
1344
- """alias for is_monotonic"""
1341
+ """
1342
+ Alias for is_monotonic.
1343
+ """
1345
1344
# mypy complains if we alias directly
1346
1345
return self .is_monotonic
1347
1346
@@ -1455,7 +1454,6 @@ def factorize(self, sort=False, na_sentinel=-1):
1455
1454
1456
1455
Examples
1457
1456
--------
1458
-
1459
1457
>>> x = pd.Series([1, 2, 3])
1460
1458
>>> x
1461
1459
0 1
0 commit comments