本文整理汇总了Python中pandas.core.common.is_bool_indexer方法的典型用法代码示例。如果您正苦于以下问题:Python common.is_bool_indexer方法的具体用法?Python common.is_bool_indexer怎么用?Python common.is_bool_indexer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandas.core.common
的用法示例。
在下文中一共展示了common.is_bool_indexer方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _multi_take_opportunity
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def _multi_take_opportunity(self, tup):
"""
Check whether there is the possibility to use ``_multi_take``.
Currently the limit is that all axes being indexed must be indexed with
list-likes.
Parameters
----------
tup : tuple
Tuple of indexers, one per axis
Returns
-------
boolean: Whether the current indexing can be passed through _multi_take
"""
if not all(is_list_like_indexer(x) for x in tup):
return False
# just too complicated
if any(com.is_bool_indexer(x) for x in tup):
return False
return True
示例2: check_bool_indexer
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def check_bool_indexer(ax, key):
# boolean indexing, need to check that the data are aligned, otherwise
# disallowed
# this function assumes that is_bool_indexer(key) == True
result = key
if isinstance(key, ABCSeries) and not key.index.equals(ax):
result = result.reindex(ax)
mask = isna(result._values)
if mask.any():
raise IndexingError('Unalignable boolean Series provided as '
'indexer (index of the boolean Series and of '
'the indexed object do not match')
result = result.astype(bool)._values
elif is_sparse(result):
result = result.to_dense()
result = np.asarray(result, dtype=bool)
else:
# is_bool_indexer has already checked for nulls in the case of an
# object array key, so no check needed here
result = np.asarray(result, dtype=bool)
return result
示例3: get_value
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def get_value(self, series, key):
if com.is_bool_indexer(key):
loc = key
elif is_list_like(key):
loc = self.get_indexer(key)
elif isinstance(key, slice):
if not (key.step is None or key.step == 1):
raise ValueError("cannot support not-default step in a slice")
try:
loc = self.get_loc(key)
except TypeError:
# we didn't find exact intervals or are non-unique
msg = "unable to slice with this key: {key}".format(key=key)
raise ValueError(msg)
else:
loc = self.get_loc(key)
return series.iloc[loc]
示例4: get_value
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def get_value(self, series, key):
if com.is_bool_indexer(key):
loc = key
elif is_list_like(key):
loc = self.get_indexer(key)
elif isinstance(key, slice):
if not (key.step is None or key.step == 1):
raise ValueError("cannot support not-default "
"step in a slice")
try:
loc = self.get_loc(key)
except TypeError:
# we didn't find exact intervals
# or are non-unique
raise ValueError("unable to slice with "
"this key: {}".format(key))
else:
loc = self.get_loc(key)
return series.iloc[loc]
示例5: test_mask_with_boolean
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def test_mask_with_boolean(index):
s = Series(range(3))
idx = Categorical([True, False, True])
if index:
idx = CategoricalIndex(idx)
assert com.is_bool_indexer(idx)
result = s[idx]
expected = s[idx.astype('object')]
tm.assert_series_equal(result, expected)
示例6: __getitem__
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def __getitem__(self, key):
if isinstance(key, tuple):
if len(key) > 1:
raise IndexError("too many indices for array.")
key = key[0]
if is_integer(key):
return self._get_val_at(key)
elif isinstance(key, tuple):
data_slice = self.values[key]
elif isinstance(key, slice):
# special case to preserve dtypes
if key == slice(None):
return self.copy()
# TODO: this logic is surely elsewhere
# TODO: this could be more efficient
indices = np.arange(len(self), dtype=np.int32)[key]
return self.take(indices)
else:
# TODO: I think we can avoid densifying when masking a
# boolean SparseArray with another. Need to look at the
# key's fill_value for True / False, and then do an intersection
# on the indicies of the sp_values.
if isinstance(key, SparseArray):
if is_bool_dtype(key):
key = key.to_dense()
else:
key = np.asarray(key)
if com.is_bool_indexer(key) and len(self) == len(key):
return self.take(np.arange(len(key), dtype=np.int32)[key])
elif hasattr(key, '__len__'):
return self.take(key)
else:
raise ValueError("Cannot slice with '{}'".format(key))
return type(self)(data_slice, kind=self.kind)
示例7: __getitem__
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def __getitem__(self, key):
"""
Override numpy.ndarray's __getitem__ method to work as desired.
This function adds lists and Series as valid boolean indexers
(ndarrays only supports ndarray with dtype=bool).
If resulting ndim != 1, plain ndarray is returned instead of
corresponding `Index` subclass.
"""
# There's no custom logic to be implemented in __getslice__, so it's
# not overloaded intentionally.
getitem = self._data.__getitem__
promote = self._shallow_copy
if is_scalar(key):
key = com.cast_scalar_indexer(key)
return getitem(key)
if isinstance(key, slice):
# This case is separated from the conditional above to avoid
# pessimization of basic indexing.
return promote(getitem(key))
if com.is_bool_indexer(key):
key = np.asarray(key, dtype=bool)
key = com.values_from_object(key)
result = getitem(key)
if not is_scalar(result):
return promote(result)
else:
return result
示例8: __getitem__
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def __getitem__(self, key):
if is_scalar(key):
key = com.cast_scalar_indexer(key)
retval = []
for lev, level_codes in zip(self.levels, self.codes):
if level_codes[key] == -1:
retval.append(np.nan)
else:
retval.append(lev[level_codes[key]])
return tuple(retval)
else:
if com.is_bool_indexer(key):
key = np.asarray(key, dtype=bool)
sortorder = self.sortorder
else:
# cannot be sure whether the result will be sorted
sortorder = None
if isinstance(key, Index):
key = np.asarray(key)
new_codes = [level_codes[key] for level_codes in self.codes]
return MultiIndex(levels=self.levels, codes=new_codes,
names=self.names, sortorder=sortorder,
verify_integrity=False)
示例9: _validate_key
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def _validate_key(self, key, axis):
if isinstance(key, slice):
return True
elif com.is_bool_indexer(key):
return True
elif is_list_like_indexer(key):
return True
else:
self._convert_scalar_indexer(key, axis)
return True
示例10: _getitem_axis
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if isinstance(key, slice):
return self._get_slice_axis(key, axis=axis)
if isinstance(key, list):
key = np.asarray(key)
if com.is_bool_indexer(key):
self._validate_key(key, axis)
return self._getbool_axis(key, axis=axis)
# a list of integers
elif is_list_like_indexer(key):
return self._get_list_axis(key, axis=axis)
# a single integer
else:
if not is_integer(key):
raise TypeError("Cannot index by location index with a "
"non-integer key")
# validate the location
self._validate_integer(key, axis)
return self._get_loc(key, axis=axis)
示例11: __getitem__
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def __getitem__(self, key):
"""
Override numpy.ndarray's __getitem__ method to work as desired.
This function adds lists and Series as valid boolean indexers
(ndarrays only supports ndarray with dtype=bool).
If resulting ndim != 1, plain ndarray is returned instead of
corresponding `Index` subclass.
"""
# There's no custom logic to be implemented in __getslice__, so it's
# not overloaded intentionally.
getitem = self._data.__getitem__
promote = self._shallow_copy
if is_scalar(key):
return getitem(key)
if isinstance(key, slice):
# This case is separated from the conditional above to avoid
# pessimization of basic indexing.
return promote(getitem(key))
if com.is_bool_indexer(key):
key = np.asarray(key)
key = com._values_from_object(key)
result = getitem(key)
if not is_scalar(result):
return promote(result)
else:
return result
示例12: __getitem__
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def __getitem__(self, key):
if is_scalar(key):
retval = []
for lev, lab in zip(self.levels, self.labels):
if lab[key] == -1:
retval.append(np.nan)
else:
retval.append(lev[lab[key]])
return tuple(retval)
else:
if com.is_bool_indexer(key):
key = np.asarray(key)
sortorder = self.sortorder
else:
# cannot be sure whether the result will be sorted
sortorder = None
if isinstance(key, Index):
key = np.asarray(key)
new_labels = [lab[key] for lab in self.labels]
return MultiIndex(levels=self.levels, labels=new_labels,
names=self.names, sortorder=sortorder,
verify_integrity=False)
示例13: _getitem_axis
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def _getitem_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
if isinstance(key, slice):
return self._get_slice_axis(key, axis=axis)
if isinstance(key, list):
key = np.asarray(key)
if com.is_bool_indexer(key):
self._validate_key(key, axis)
return self._getbool_axis(key, axis=axis)
# a list of integers
elif is_list_like_indexer(key):
return self._get_list_axis(key, axis=axis)
# a single integer
else:
key = self._convert_scalar_indexer(key, axis)
if not is_integer(key):
raise TypeError("Cannot index by location index with a "
"non-integer key")
# validate the location
self._validate_integer(key, axis)
return self._get_loc(key, axis=axis)
示例14: _getitem_array
# 需要导入模块: from pandas.core import common [as 别名]
# 或者: from pandas.core.common import is_bool_indexer [as 别名]
def _getitem_array(self, key):
# TODO: dont convert to pandas for array indexing
if isinstance(key, Series):
key = key._to_pandas()
if is_bool_indexer(key):
if isinstance(key, pandas.Series) and not key.index.equals(self.index):
warnings.warn(
"Boolean Series key will be reindexed to match DataFrame index.",
PendingDeprecationWarning,
stacklevel=3,
)
elif len(key) != len(self.index):
raise ValueError(
"Item wrong length {} instead of {}.".format(
len(key), len(self.index)
)
)
key = check_bool_indexer(self.index, key)
# We convert to a RangeIndex because getitem_row_array is expecting a list
# of indices, and RangeIndex will give us the exact indices of each boolean
# requested.
key = pandas.RangeIndex(len(self.index))[key]
if len(key):
return DataFrame(
query_compiler=self._query_compiler.getitem_row_array(key)
)
else:
return DataFrame(columns=self.columns)
else:
if any(k not in self.columns for k in key):
raise KeyError(
"{} not index".format(
str([k for k in key if k not in self.columns]).replace(",", "")
)
)
return DataFrame(
query_compiler=self._query_compiler.getitem_column_array(key)
)