11"""
22Base and utility classes for pandas objects.
33"""
4+
45import builtins
56import textwrap
67from typing import Dict , FrozenSet , List , Optional , Union
4546
4647
4748class PandasObject (DirNamesMixin ):
48- """baseclass for various pandas objects"""
49+ """
50+ Baseclass for various pandas objects.
51+ """
4952
5053 @property
5154 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+ """
5358 return type (self )
5459
5560 def __repr__ (self ) -> str :
@@ -77,16 +82,14 @@ def __sizeof__(self):
7782 """
7883 if hasattr (self , "memory_usage" ):
7984 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 ())
8386
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'
8688 return super ().__sizeof__ ()
8789
8890 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.
9093
9194 Used by type checkers.
9295 """
@@ -95,7 +98,8 @@ def _ensure_type(self: T, obj) -> T:
9598
9699
97100class NoNewAttributesMixin :
98- """Mixin which prevents adding new attributes.
101+ """
102+ Mixin which prevents adding new attributes.
99103
100104 Prevents additional attributes via xxx.attribute = "something" after a
101105 call to `self.__freeze()`. Mainly used to prevent the user from using
@@ -106,7 +110,9 @@ class NoNewAttributesMixin:
106110 """
107111
108112 def _freeze (self ):
109- """Prevents setting additional attributes"""
113+ """
114+ Prevents setting additional attributes.
115+ """
110116 object .__setattr__ (self , "__frozen" , True )
111117
112118 # prevent adding any attribute via s.xxx.new_attribute = ...
@@ -180,14 +186,12 @@ class SelectionMixin:
180186 @property
181187 def _selection_name (self ):
182188 """
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.
186193 """
187- if self ._selection is None :
188- return None # 'result'
189- else :
190- return self ._selection
194+ return self ._selection
191195
192196 @property
193197 def _selection_list (self ):
@@ -199,7 +203,6 @@ def _selection_list(self):
199203
200204 @cache_readonly
201205 def _selected_obj (self ):
202-
203206 if self ._selection is None or isinstance (self .obj , ABCSeries ):
204207 return self .obj
205208 else :
@@ -246,12 +249,11 @@ def _gotitem(self, key, ndim: int, subset=None):
246249
247250 Parameters
248251 ----------
249- key : string / list of selections
252+ key : str / list of selections
250253 ndim : 1,2
251254 requested ndim of result
252255 subset : object, default None
253256 subset to act on
254-
255257 """
256258 raise AbstractMethodError (self )
257259
@@ -266,7 +268,6 @@ def _try_aggregate_string_function(self, arg: str, *args, **kwargs):
266268 - try to find a function (or attribute) on ourselves
267269 - try to find a numpy function
268270 - raise
269-
270271 """
271272 assert isinstance (arg , str )
272273
@@ -585,7 +586,6 @@ def _shallow_copy(self, obj, **kwargs):
585586 """
586587 return a new object with the replacement attributes
587588 """
588-
589589 if isinstance (obj , self ._constructor ):
590590 obj = obj .obj
591591 for attr in self ._attributes :
@@ -669,8 +669,7 @@ def item(self):
669669
670670 if len (self ) == 1 :
671671 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" )
674673
675674 @property
676675 def nbytes (self ) -> int :
@@ -735,7 +734,6 @@ def array(self) -> ExtensionArray:
735734
736735 Examples
737736 --------
738-
739737 For regular NumPy types like int, and float, a PandasArray
740738 is returned.
741739
@@ -851,12 +849,11 @@ def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs):
851849 """
852850 if is_extension_array_dtype (self .dtype ):
853851 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+ )
860857
861858 result = np .asarray (self ._values , dtype = dtype )
862859 # TODO(GH-24345): Avoid potential double copy
@@ -1076,7 +1073,9 @@ def _reduce(
10761073 filter_type = None ,
10771074 ** kwds ,
10781075 ):
1079- """ perform the reduction type operation if we can """
1076+ """
1077+ Perform the reduction type operation if we can.
1078+ """
10801079 func = getattr (self , name , None )
10811080 if func is None :
10821081 raise TypeError (
@@ -1103,9 +1102,7 @@ def _map_values(self, mapper, na_action=None):
11031102 The output of the mapping function applied to the index.
11041103 If the function returns a tuple with more than one element
11051104 a MultiIndex will be returned.
1106-
11071105 """
1108-
11091106 # we can fastpath dict/Series to an efficient map
11101107 # as we know that we are not going to have to yield
11111108 # python types
@@ -1341,7 +1338,9 @@ def is_monotonic(self) -> bool:
13411338
13421339 @property
13431340 def is_monotonic_increasing (self ) -> bool :
1344- """alias for is_monotonic"""
1341+ """
1342+ Alias for is_monotonic.
1343+ """
13451344 # mypy complains if we alias directly
13461345 return self .is_monotonic
13471346
@@ -1455,7 +1454,6 @@ def factorize(self, sort=False, na_sentinel=-1):
14551454
14561455 Examples
14571456 --------
1458-
14591457 >>> x = pd.Series([1, 2, 3])
14601458 >>> x
14611459 0 1
0 commit comments