Skip to content

Commit 9427864

Browse files
committed
edit relevant classes and write _enforce_bool_type function
1 parent 5033a4a commit 9427864

File tree

8 files changed

+58
-7
lines changed

8 files changed

+58
-7
lines changed

pandas/computation/eval.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from pandas.computation.scope import _ensure_scope
1212
from pandas.compat import string_types
1313
from pandas.computation.engines import _engines
14+
from pandas.core import common as com
1415

1516

1617
def _check_engine(engine):
@@ -231,6 +232,7 @@ def eval(expr, parser='pandas', engine=None, truediv=True,
231232
pandas.DataFrame.query
232233
pandas.DataFrame.eval
233234
"""
235+
inplace = com.enforce_bool_type(inplace)
234236
first_expr = True
235237
if isinstance(expr, string_types):
236238
exprs = [e for e in expr.splitlines() if e != '']

pandas/core/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1177,6 +1177,7 @@ def searchsorted(self, key, side='left', sorter=None):
11771177
False: 'first'})
11781178
@Appender(_shared_docs['drop_duplicates'] % _indexops_doc_kwargs)
11791179
def drop_duplicates(self, keep='first', inplace=False):
1180+
inplace = com._enforce_bool_type(inplace)
11801181
if isinstance(self, ABCIndexClass):
11811182
if self.is_unique:
11821183
return self._shallow_copy()

pandas/core/common.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,13 @@ def is_bool_indexer(key):
205205
return False
206206

207207

208+
def _enforce_bool_type(value):
209+
if not isinstance(value, bool):
210+
raise ValueError('Expected type bool, received type %s.' %\
211+
type(value).__name__)
212+
return value
213+
214+
208215
def _default_index(n):
209216
from pandas.core.index import RangeIndex
210217
return RangeIndex(0, n, name=None)

pandas/core/frame.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@
6161
_default_index,
6262
_values_from_object,
6363
_maybe_box_datetimelike,
64-
_dict_compat)
64+
_dict_compat,
65+
_enforce_bool_type)
6566
from pandas.core.generic import NDFrame, _shared_docs
6667
from pandas.core.index import Index, MultiIndex, _ensure_index
6768
from pandas.core.indexing import (maybe_droplevels, convert_to_index_sliceable,
@@ -2199,6 +2200,7 @@ def query(self, expr, inplace=False, **kwargs):
21992200
>>> df.query('a > b')
22002201
>>> df[df.a > df.b] # same result as the previous expression
22012202
"""
2203+
inplace = _enforce_bool_type(inplace)
22022204
if not isinstance(expr, compat.string_types):
22032205
msg = "expr must be a string to be evaluated, {0} given"
22042206
raise ValueError(msg.format(type(expr)))
@@ -2265,6 +2267,7 @@ def eval(self, expr, inplace=None, **kwargs):
22652267
>>> df.eval('a + b')
22662268
>>> df.eval('c = a + b')
22672269
"""
2270+
inplace = _enforce_bool_type(inplace)
22682271
resolvers = kwargs.pop('resolvers', None)
22692272
kwargs['level'] = kwargs.pop('level', 0) + 1
22702273
if resolvers is None:
@@ -2857,6 +2860,7 @@ def set_index(self, keys, drop=True, append=False, inplace=False,
28572860
-------
28582861
dataframe : DataFrame
28592862
"""
2863+
inplace = _enforce_bool_type(inplace)
28602864
if not isinstance(keys, list):
28612865
keys = [keys]
28622866

@@ -2949,6 +2953,7 @@ def reset_index(self, level=None, drop=False, inplace=False, col_level=0,
29492953
-------
29502954
resetted : DataFrame
29512955
"""
2956+
inplace = _enforce_bool_type(inplace)
29522957
if inplace:
29532958
new_obj = self
29542959
else:
@@ -3053,6 +3058,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None,
30533058
-------
30543059
dropped : DataFrame
30553060
"""
3061+
inplace = _enforce_bool_type(inplace)
30563062
if isinstance(axis, (tuple, list)):
30573063
result = self
30583064
for ax in axis:
@@ -3116,6 +3122,7 @@ def drop_duplicates(self, subset=None, keep='first', inplace=False):
31163122
-------
31173123
deduplicated : DataFrame
31183124
"""
3125+
inplace = _enforce_bool_type(inplace)
31193126
duplicated = self.duplicated(subset, keep=keep)
31203127

31213128
if inplace:
@@ -3177,7 +3184,7 @@ def f(vals):
31773184
@Appender(_shared_docs['sort_values'] % _shared_doc_kwargs)
31783185
def sort_values(self, by, axis=0, ascending=True, inplace=False,
31793186
kind='quicksort', na_position='last'):
3180-
3187+
inplace = _enforce_bool_type(inplace)
31813188
axis = self._get_axis_number(axis)
31823189
other_axis = 0 if axis == 1 else 1
31833190

@@ -3288,7 +3295,7 @@ def sort(self, columns=None, axis=0, ascending=True, inplace=False,
32883295
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
32893296
kind='quicksort', na_position='last', sort_remaining=True,
32903297
by=None):
3291-
3298+
inplace = _enforce_bool_type(inplace)
32923299
# 10726
32933300
if by is not None:
32943301
warnings.warn("by argument to sort_index is deprecated, pls use "

pandas/core/generic.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@
3030
from pandas.core.common import (_values_from_object,
3131
_maybe_box_datetimelike,
3232
SettingWithCopyError, SettingWithCopyWarning,
33-
AbstractMethodError)
33+
AbstractMethodError,
34+
_enforce_bool_type)
3435

3536
from pandas.core.base import PandasObject
3637
from pandas.core.index import (Index, MultiIndex, _ensure_index,
@@ -732,6 +733,7 @@ def rename_axis(self, mapper, axis=0, copy=True, inplace=False):
732733
1 2 5
733734
2 3 6
734735
"""
736+
inplace = _enforce_bool_type(inplace)
735737
non_mapper = is_scalar(mapper) or (is_list_like(mapper) and not
736738
is_dict_like(mapper))
737739
if non_mapper:
@@ -1893,6 +1895,7 @@ def drop(self, labels, axis=0, level=None, inplace=False, errors='raise'):
18931895
-------
18941896
dropped : type of caller
18951897
"""
1898+
inplace = _enforce_bool_type(inplace)
18961899
axis = self._get_axis_number(axis)
18971900
axis_name = self._get_axis_name(axis)
18981901
axis, axis_ = self._get_axis(axis), axis
@@ -2041,6 +2044,7 @@ def sort_values(self, by, axis=0, ascending=True, inplace=False,
20412044
@Appender(_shared_docs['sort_index'] % dict(axes="axes", klass="NDFrame"))
20422045
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
20432046
kind='quicksort', na_position='last', sort_remaining=True):
2047+
inplace = _enforce_bool_type(inplace)
20442048
axis = self._get_axis_number(axis)
20452049
axis_name = self._get_axis_name(axis)
20462050
labels = self._get_axis(axis)
@@ -2221,7 +2225,7 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
22212225
# kinds
22222226

22232227
@Appender(_shared_docs['reindex'] % dict(axes="axes", klass="NDFrame"))
2224-
def reindex(self, *args, **kwargs):
2228+
def reindex(self, *args, **kwargs):
22252229

22262230
# construct the args
22272231
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
@@ -2814,6 +2818,7 @@ def consolidate(self, inplace=False):
28142818
-------
28152819
consolidated : type of caller
28162820
"""
2821+
inplace = _enforce_bool_type(inplace)
28172822
if inplace:
28182823
self._consolidate_inplace()
28192824
else:
@@ -3199,6 +3204,7 @@ def convert_objects(self, convert_dates=True, convert_numeric=False,
31993204
@Appender(_shared_docs['fillna'] % _shared_doc_kwargs)
32003205
def fillna(self, value=None, method=None, axis=None, inplace=False,
32013206
limit=None, downcast=None):
3207+
inplace = _enforce_bool_type(inplace)
32023208
if isinstance(value, (list, tuple)):
32033209
raise TypeError('"value" parameter must be a scalar or dict, but '
32043210
'you passed a "{0}"'.format(type(value).__name__))
@@ -3407,6 +3413,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
34073413
and play with this method to gain intuition about how it works.
34083414
34093415
"""
3416+
inplace = _enforce_bool_type(inplace)
34103417
if not is_bool(regex) and to_replace is not None:
34113418
raise AssertionError("'to_replace' must be 'None' if 'regex' is "
34123419
"not a bool")
@@ -3632,6 +3639,7 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False,
36323639
"""
36333640
Interpolate values according to different methods.
36343641
"""
3642+
inplace = _enforce_bool_type(inplace)
36353643

36363644
if self.ndim > 2:
36373645
raise NotImplementedError("Interpolate has not been implemented "
@@ -4511,6 +4519,7 @@ def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
45114519
Equivalent to public method `where`, except that `other` is not
45124520
applied as a function even if callable. Used in __setitem__.
45134521
"""
4522+
inplace = _enforce_bool_type(inplace)
45144523

45154524
cond = com._apply_if_callable(cond, self)
45164525

@@ -4778,6 +4787,7 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
47784787
def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,
47794788
try_cast=False, raise_on_error=True):
47804789

4790+
inplace = _enforce_bool_type(inplace)
47814791
cond = com._apply_if_callable(cond, self)
47824792

47834793
return self.where(~cond, other=other, inplace=inplace, axis=axis,

pandas/core/internals.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
import pandas.types.concat as _concat
4444

4545
from pandas.types.generic import ABCSeries
46-
from pandas.core.common import is_null_slice
46+
from pandas.core.common import is_null_slice, _enforce_bool_type
4747
import pandas.core.algorithms as algos
4848

4949
from pandas.core.index import Index, MultiIndex, _ensure_index
@@ -361,6 +361,7 @@ def fillna(self, value, limit=None, inplace=False, downcast=None,
361361
""" fillna on the block with the value. If we fail, then convert to
362362
ObjectBlock and try again
363363
"""
364+
inplace = com.enforce_bool_type(inplace)
364365

365366
if not self._can_hold_na:
366367
if inplace:
@@ -621,6 +622,7 @@ def replace(self, to_replace, value, inplace=False, filter=None,
621622
compatibility.
622623
"""
623624

625+
inplace = com.enforce_bool_type(inplace)
624626
original_to_replace = to_replace
625627
mask = isnull(self.values)
626628

@@ -893,6 +895,9 @@ def interpolate(self, method='pad', axis=0, index=None, values=None,
893895
inplace=False, limit=None, limit_direction='forward',
894896
fill_value=None, coerce=False, downcast=None, mgr=None,
895897
**kwargs):
898+
899+
inplace = com.enforce_bool_type(inplace)
900+
896901
def check_int_bool(self, inplace):
897902
# Only FloatBlocks will contain NaNs.
898903
# timedelta subclasses IntBlock
@@ -940,6 +945,8 @@ def _interpolate_with_fill(self, method='pad', axis=0, inplace=False,
940945
downcast=None, mgr=None):
941946
""" fillna but using the interpolate machinery """
942947

948+
inplace = com.enforce_bool_type(inplace)
949+
943950
# if we are coercing, then don't force the conversion
944951
# if the block can't hold the type
945952
if coerce:
@@ -966,6 +973,7 @@ def _interpolate(self, method=None, index=None, values=None,
966973
mgr=None, **kwargs):
967974
""" interpolate using scipy wrappers """
968975

976+
inplace = com.enforce_bool_type(inplace)
969977
data = self.values if inplace else self.values.copy()
970978

971979
# only deal with floats
@@ -1487,6 +1495,7 @@ def putmask(self, mask, new, align=True, inplace=False, axis=0,
14871495
-------
14881496
a new block(s), the result of the putmask
14891497
"""
1498+
inplace = com.enforce_bool_type(inplace)
14901499

14911500
# use block's copy logic.
14921501
# .values may be an Index which does shallow copy by default
@@ -1774,6 +1783,7 @@ def should_store(self, value):
17741783

17751784
def replace(self, to_replace, value, inplace=False, filter=None,
17761785
regex=False, mgr=None):
1786+
inplace = com.enforce_bool_type(inplace)
17771787
to_replace_values = np.atleast_1d(to_replace)
17781788
if not np.can_cast(to_replace_values, bool):
17791789
return self
@@ -1954,6 +1964,9 @@ def replace(self, to_replace, value, inplace=False, filter=None,
19541964

19551965
def _replace_single(self, to_replace, value, inplace=False, filter=None,
19561966
regex=False, convert=True, mgr=None):
1967+
1968+
inplace = com.enforce_bool_type(inplace)
1969+
19571970
# to_replace is regex compilable
19581971
to_rep_re = regex and is_re_compilable(to_replace)
19591972

@@ -3177,6 +3190,8 @@ def replace_list(self, src_list, dest_list, inplace=False, regex=False,
31773190
mgr=None):
31783191
""" do a list replace """
31793192

3193+
inplace = com.enforce_bool_type(inplace)
3194+
31803195
if mgr is None:
31813196
mgr = self
31823197

pandas/core/series.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@
4040
_maybe_match_name,
4141
SettingWithCopyError,
4242
_maybe_box_datetimelike,
43-
_dict_compat)
43+
_dict_compat,
44+
_enforce_bool_type)
4445
from pandas.core.index import (Index, MultiIndex, InvalidIndexError,
4546
Float64Index, _ensure_index)
4647
from pandas.core.indexing import check_bool_indexer, maybe_convert_indices
@@ -971,6 +972,7 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False):
971972
----------
972973
resetted : DataFrame, or Series if drop == True
973974
"""
975+
inplace = _enforce_bool_type(inplace)
974976
if drop:
975977
new_index = _default_index(len(self))
976978
if level is not None and isinstance(self.index, MultiIndex):
@@ -1171,6 +1173,7 @@ def _set_name(self, name, inplace=False):
11711173
inplace : bool
11721174
whether to modify `self` directly or return a copy
11731175
"""
1176+
inplace = _enforce_bool_type(inplace)
11741177
ser = self if inplace else self.copy()
11751178
ser.name = name
11761179
return ser
@@ -1723,6 +1726,7 @@ def update(self, other):
17231726
def sort_values(self, axis=0, ascending=True, inplace=False,
17241727
kind='quicksort', na_position='last'):
17251728

1729+
inplace = _enforce_bool_type(inplace)
17261730
axis = self._get_axis_number(axis)
17271731

17281732
# GH 5856/5853
@@ -1775,6 +1779,7 @@ def _try_kind_sort(arr):
17751779
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
17761780
sort_remaining=True):
17771781

1782+
inplace = _enforce_bool_type(inplace)
17781783
axis = self._get_axis_number(axis)
17791784
index = self.index
17801785
if level is not None:
@@ -2349,6 +2354,7 @@ def align(self, other, join='outer', axis=None, level=None, copy=True,
23492354

23502355
@Appender(generic._shared_docs['rename'] % _shared_doc_kwargs)
23512356
def rename(self, index=None, **kwargs):
2357+
kwargs['inplace'] = _enforce_bool_type(kwargs['inplace'])
23522358
non_mapping = is_scalar(index) or (is_list_like(index) and
23532359
not is_dict_like(index))
23542360
if non_mapping:
@@ -2632,6 +2638,7 @@ def dropna(self, axis=0, inplace=False, **kwargs):
26322638
inplace : boolean, default False
26332639
Do operation in place.
26342640
"""
2641+
inplace = _enforce_bool_type(inplace)
26352642
kwargs.pop('how', None)
26362643
if kwargs:
26372644
raise TypeError('dropna() got an unexpected keyword '

pandas/sparse/list.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from pandas.formats.printing import pprint_thing
55

66
from pandas.types.common import is_scalar
7+
from pands.core.common import _enforce_bool_type
78
from pandas.sparse.array import SparseArray
89
import pandas._sparse as splib
910

@@ -78,6 +79,7 @@ def consolidate(self, inplace=True):
7879
If inplace=False, new object, otherwise reference to existing
7980
object
8081
"""
82+
inplace = com.enforce_bool_type(inplace)
8183
if not inplace:
8284
result = self.copy()
8385
else:

0 commit comments

Comments
 (0)