Skip to content

Commit 2572d95

Browse files
committed
Use pandas.core.common for None checks
1 parent 7db7f82 commit 2572d95

21 files changed

+83
-73
lines changed

pandas/core/common.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,20 @@ def _any_none(*args):
233233
return False
234234

235235

236+
def _all_none(*args):
237+
for arg in args:
238+
if arg is not None:
239+
return False
240+
return True
241+
242+
243+
def _any_not_none(*args):
244+
for arg in args:
245+
if arg is not None:
246+
return True
247+
return False
248+
249+
236250
def _all_not_none(*args):
237251
for arg in args:
238252
if arg is None:
@@ -459,13 +473,6 @@ def _apply_if_callable(maybe_callable, obj, **kwargs):
459473
return maybe_callable
460474

461475

462-
def _all_none(*args):
463-
for arg in args:
464-
if arg is not None:
465-
return False
466-
return True
467-
468-
469476
def _where_compat(mask, arr1, arr2):
470477
if arr1.dtype == _NS_DTYPE and arr2.dtype == _NS_DTYPE:
471478
new_vals = np.where(mask, arr1.view('i8'), arr2.view('i8'))

pandas/core/generic.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,9 @@
2929
from pandas.core.dtypes.missing import isna, notna
3030
from pandas.core.dtypes.generic import ABCSeries, ABCPanel, ABCDataFrame
3131

32-
from pandas.core.common import (_values_from_object,
33-
_maybe_box_datetimelike,
34-
SettingWithCopyError, SettingWithCopyWarning,
35-
AbstractMethodError)
32+
from pandas.core.common import (_count_not_none, _maybe_box_datetimelike,
33+
_values_from_object, AbstractMethodError,
34+
SettingWithCopyError, SettingWithCopyWarning)
3635

3736
from pandas.core.base import PandasObject, SelectionMixin
3837
from pandas.core.index import (Index, MultiIndex, _ensure_index,
@@ -3126,7 +3125,7 @@ def filter(self, items=None, like=None, regex=None, axis=None):
31263125
"""
31273126
import re
31283127

3129-
nkw = sum([x is not None for x in [items, like, regex]])
3128+
nkw = _count_not_none(items, like, regex)
31303129
if nkw > 1:
31313130
raise TypeError('Keyword arguments `items`, `like`, or `regex` '
31323131
'are mutually exclusive')

pandas/core/groupby.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@
3939
from pandas.core.dtypes.missing import isna, notna, _maybe_fill
4040

4141
from pandas.core.common import (_values_from_object, AbstractMethodError,
42-
_default_index)
42+
_default_index, _not_none, _get_callable_name,
43+
_asarray_tuplesafe)
4344

4445
from pandas.core.base import (PandasObject, SelectionMixin, GroupByError,
4546
DataError, SpecificationError)
@@ -60,7 +61,6 @@
6061
from pandas.util._validators import validate_kwargs
6162

6263
import pandas.core.algorithms as algorithms
63-
import pandas.core.common as com
6464
from pandas.core.config import option_context
6565

6666
from pandas.plotting._core import boxplot_frame_groupby
@@ -877,10 +877,9 @@ def _concat_objects(self, keys, values, not_indexed_same=False):
877877
def reset_identity(values):
878878
# reset the identities of the components
879879
# of the values to prevent aliasing
880-
for v in values:
881-
if v is not None:
882-
ax = v._get_axis(self.axis)
883-
ax._reset_identity()
880+
for v in _not_none(*values):
881+
ax = v._get_axis(self.axis)
882+
ax._reset_identity()
884883
return values
885884

886885
if not not_indexed_same:
@@ -1806,7 +1805,7 @@ def apply(self, f, data, axis=0):
18061805
group_keys = self._get_group_keys()
18071806

18081807
# oh boy
1809-
f_name = com._get_callable_name(f)
1808+
f_name = _get_callable_name(f)
18101809
if (f_name not in _plotting_methods and
18111810
hasattr(splitter, 'fast_apply') and axis == 0):
18121811
try:
@@ -2533,7 +2532,7 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None,
25332532
self.grouper = self.obj[self.name]
25342533

25352534
elif isinstance(self.grouper, (list, tuple)):
2536-
self.grouper = com._asarray_tuplesafe(self.grouper)
2535+
self.grouper = _asarray_tuplesafe(self.grouper)
25372536

25382537
# a passed Categorical
25392538
elif is_categorical_dtype(self.grouper):
@@ -2739,7 +2738,7 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
27392738
if not any_callable and not all_in_columns_index and \
27402739
not any_arraylike and not any_groupers and \
27412740
match_axis_length and level is None:
2742-
keys = [com._asarray_tuplesafe(keys)]
2741+
keys = [_asarray_tuplesafe(keys)]
27432742

27442743
if isinstance(level, (tuple, list)):
27452744
if key is None:
@@ -3028,7 +3027,7 @@ def _aggregate_multiple_funcs(self, arg, _level):
30283027
columns.append(f)
30293028
else:
30303029
# protect against callables without names
3031-
columns.append(com._get_callable_name(f))
3030+
columns.append(_get_callable_name(f))
30323031
arg = lzip(columns, arg)
30333032

30343033
results = {}
@@ -3686,14 +3685,13 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
36863685
key_names = self.grouper.names
36873686

36883687
# GH12824.
3689-
def first_non_None_value(values):
3688+
def first_not_none(values):
36903689
try:
3691-
v = next(v for v in values if v is not None)
3690+
return next(_not_none(*values))
36923691
except StopIteration:
36933692
return None
3694-
return v
36953693

3696-
v = first_non_None_value(values)
3694+
v = first_not_none(values)
36973695

36983696
if v is None:
36993697
# GH9684. If all values are None, then this will throw an error.
@@ -3726,7 +3724,7 @@ def first_non_None_value(values):
37263724
key_index = None
37273725

37283726
# make Nones an empty object
3729-
v = first_non_None_value(values)
3727+
v = first_not_none(values)
37303728
if v is None:
37313729
return DataFrame()
37323730
elif isinstance(v, NDFrame):

pandas/core/indexes/api.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def _get_consensus_names(indexes):
123123
# find the non-none names, need to tupleify to make
124124
# the set hashable, then reverse on return
125125
consensus_names = set([tuple(i.names) for i in indexes
126-
if any(n is not None for n in i.names)])
126+
if com._any_not_none(*i.names)])
127127
if len(consensus_names) == 1:
128128
return list(list(consensus_names)[0])
129129
return [None] * indexes[0].nlevels

pandas/core/indexes/base.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,15 @@
4242
needs_i8_conversion,
4343
is_iterator, is_list_like,
4444
is_scalar)
45-
from pandas.core.common import (is_bool_indexer,
46-
_values_from_object,
47-
_asarray_tuplesafe)
45+
from pandas.core.common import (is_bool_indexer, _values_from_object,
46+
_asarray_tuplesafe, _not_none,
47+
_index_labels_to_array)
4848

4949
from pandas.core.base import PandasObject, IndexOpsMixin
5050
import pandas.core.base as base
5151
from pandas.util._decorators import (
5252
Appender, Substitution, cache_readonly, deprecate_kwarg)
5353
from pandas.core.indexes.frozen import FrozenList
54-
import pandas.core.common as com
5554
import pandas.core.dtypes.concat as _concat
5655
import pandas.core.missing as missing
5756
import pandas.core.algorithms as algos
@@ -3145,8 +3144,8 @@ def _join_multi(self, other, how, return_indexers=True):
31453144
other_is_mi = isinstance(other, MultiIndex)
31463145

31473146
# figure out join names
3148-
self_names = [n for n in self.names if n is not None]
3149-
other_names = [n for n in other.names if n is not None]
3147+
self_names = _not_none(*self.names)
3148+
other_names = _not_none(*other.names)
31503149
overlap = list(set(self_names) & set(other_names))
31513150

31523151
# need at least 1 in common, but not more than 1
@@ -3691,7 +3690,7 @@ def drop(self, labels, errors='raise'):
36913690
-------
36923691
dropped : Index
36933692
"""
3694-
labels = com._index_labels_to_array(labels)
3693+
labels = _index_labels_to_array(labels)
36953694
indexer = self.get_indexer(labels)
36963695
mask = indexer == -1
36973696
if mask.any():

pandas/core/indexes/multi.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
is_scalar)
2222
from pandas.core.dtypes.missing import isna, array_equivalent
2323
from pandas.errors import PerformanceWarning, UnsortedIndexError
24-
from pandas.core.common import (_values_from_object,
24+
from pandas.core.common import (_any_not_none,
25+
_values_from_object,
2526
is_bool_indexer,
2627
is_null_slice,
2728
is_true_slices)
@@ -509,7 +510,7 @@ def _format_attrs(self):
509510
max_seq_items=False)),
510511
('labels', ibase.default_pprint(self._labels,
511512
max_seq_items=False))]
512-
if not all(name is None for name in self.names):
513+
if _any_not_none(*self.names):
513514
attrs.append(('names', ibase.default_pprint(self.names)))
514515
if self.sortorder is not None:
515516
attrs.append(('sortorder', ibase.default_pprint(self.sortorder)))

pandas/core/indexes/range.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from pandas import compat
1313
from pandas.compat import lrange, range
1414
from pandas.compat.numpy import function as nv
15+
from pandas.core.common import _all_none
1516
from pandas.core.indexes.base import Index, _index_shared_docs
1617
from pandas.util._decorators import Appender, cache_readonly
1718
import pandas.core.dtypes.concat as _concat
@@ -83,7 +84,7 @@ def _ensure_int(value, field):
8384

8485
return new_value
8586

86-
if start is None and stop is None and step is None:
87+
if _all_none(start, stop, step):
8788
msg = "RangeIndex(...) must be called with integers"
8889
raise TypeError(msg)
8990
elif start is None:

pandas/core/panel.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
is_string_like, is_scalar)
1616
from pandas.core.dtypes.missing import notna
1717

18-
import pandas.core.common as com
1918
import pandas.core.ops as ops
2019
import pandas.core.missing as missing
2120
from pandas import compat
2221
from pandas.compat import (map, zip, range, u, OrderedDict)
2322
from pandas.compat.numpy import function as nv
24-
from pandas.core.common import _try_sort, _default_index
23+
from pandas.core.common import (_try_sort, _default_index, _all_not_none,
24+
_any_not_none, _apply_if_callable)
2525
from pandas.core.frame import DataFrame
2626
from pandas.core.generic import NDFrame, _shared_docs
2727
from pandas.core.index import (Index, MultiIndex, _ensure_index,
@@ -165,7 +165,7 @@ def _init_data(self, data, copy, dtype, **kwargs):
165165

166166
axes = None
167167
if isinstance(data, BlockManager):
168-
if any(x is not None for x in passed_axes):
168+
if _any_not_none(*passed_axes):
169169
axes = [x if x is not None else y
170170
for x, y in zip(passed_axes, data.axes)]
171171
mgr = data
@@ -177,7 +177,7 @@ def _init_data(self, data, copy, dtype, **kwargs):
177177
mgr = self._init_matrix(data, passed_axes, dtype=dtype, copy=copy)
178178
copy = False
179179
dtype = None
180-
elif is_scalar(data) and all(x is not None for x in passed_axes):
180+
elif is_scalar(data) and _all_not_none(*passed_axes):
181181
values = cast_scalar_to_array([len(x) for x in passed_axes],
182182
data, dtype=dtype)
183183
mgr = self._init_matrix(values, passed_axes, dtype=values.dtype,
@@ -278,7 +278,7 @@ def from_dict(cls, data, intersect=False, orient='items', dtype=None):
278278
return cls(**d)
279279

280280
def __getitem__(self, key):
281-
key = com._apply_if_callable(key, self)
281+
key = _apply_if_callable(key, self)
282282

283283
if isinstance(self._info_axis, MultiIndex):
284284
return self._getitem_multilevel(key)
@@ -593,7 +593,7 @@ def _box_item_values(self, key, values):
593593
return self._constructor_sliced(values, **d)
594594

595595
def __setitem__(self, key, value):
596-
key = com._apply_if_callable(key, self)
596+
key = _apply_if_callable(key, self)
597597
shape = tuple(self.shape)
598598
if isinstance(value, self._constructor_sliced):
599599
value = value.reindex(
@@ -615,7 +615,9 @@ def __setitem__(self, key, value):
615615

616616
def _unpickle_panel_compat(self, state): # pragma: no cover
617617
"Unpickle the panel"
618-
_unpickle = com._unpickle_array
618+
from pandas.io.pickle import _unpickle_array
619+
620+
_unpickle = _unpickle_array
619621
vals, items, major, minor = state
620622

621623
items = _unpickle(items)

pandas/core/reshape/concat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ def __init__(self, objs, axis=0, join='outer', join_axes=None,
241241
raise ValueError('No objects to concatenate')
242242

243243
if keys is None:
244-
objs = [obj for obj in objs if obj is not None]
244+
objs = list(com._not_none(*objs))
245245
else:
246246
# #1649
247247
clean_keys = []

pandas/core/reshape/merge.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1550,4 +1550,4 @@ def _should_fill(lname, rname):
15501550

15511551

15521552
def _any(x):
1553-
return x is not None and len(x) > 0 and any([y is not None for y in x])
1553+
return x is not None and com._any_not_none(*x)

pandas/core/series.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@
4545
SettingWithCopyError,
4646
_maybe_box_datetimelike,
4747
_dict_compat,
48-
standardize_mapping)
48+
standardize_mapping,
49+
_any_none)
4950
from pandas.core.index import (Index, MultiIndex, InvalidIndexError,
5051
Float64Index, _ensure_index)
5152
from pandas.core.indexing import check_bool_indexer, maybe_convert_indices
@@ -713,7 +714,7 @@ def _get_with(self, key):
713714

714715
def _get_values_tuple(self, key):
715716
# mpl hackaround
716-
if any(k is None for k in key):
717+
if _any_none(*key):
717718
return self._get_values(key)
718719

719720
if not isinstance(self.index, MultiIndex):

pandas/core/window.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
from pandas.core.base import (PandasObject, SelectionMixin,
3434
GroupByMixin)
35-
import pandas.core.common as com
35+
from pandas.core.common import _asarray_tuplesafe, _count_not_none
3636
import pandas._libs.window as _window
3737

3838
from pandas import compat
@@ -535,7 +535,7 @@ def _prep_window(self, **kwargs):
535535

536536
window = self._get_window()
537537
if isinstance(window, (list, tuple, np.ndarray)):
538-
return com._asarray_tuplesafe(window).astype(float)
538+
return _asarray_tuplesafe(window).astype(float)
539539
elif is_integer(window):
540540
import scipy.signal as sig
541541

@@ -1972,8 +1972,7 @@ def dataframe_from_int_dict(data, frame_template):
19721972

19731973

19741974
def _get_center_of_mass(com, span, halflife, alpha):
1975-
valid_count = len([x for x in [com, span, halflife, alpha]
1976-
if x is not None])
1975+
valid_count = _count_not_none(com, span, halflife, alpha)
19771976
if valid_count > 1:
19781977
raise ValueError("com, span, halflife, and alpha "
19791978
"are mutually exclusive")

pandas/io/formats/excel.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from pandas.compat import reduce
1111
from pandas.io.formats.css import CSSResolver, CSSWarning
1212
from pandas.io.formats.printing import pprint_thing
13+
from pandas.core.common import _any_not_none
1314
from pandas.core.dtypes.common import is_float
1415
import pandas._libs.lib as lib
1516
from pandas import Index, MultiIndex, PeriodIndex
@@ -548,8 +549,7 @@ def _format_hierarchical_rows(self):
548549
self.rowcounter += 1
549550

550551
# if index labels are not empty go ahead and dump
551-
if (any(x is not None for x in index_labels) and
552-
self.header is not False):
552+
if _any_not_none(*index_labels) and self.header is not False:
553553

554554
for cidx, name in enumerate(index_labels):
555555
yield ExcelCell(self.rowcounter - 1, cidx, name,

0 commit comments

Comments
 (0)