本文整理汇总了Python中operator.index方法的典型用法代码示例。如果您正苦于以下问题:Python operator.index方法的具体用法?Python operator.index怎么用?Python operator.index使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类operator
的用法示例。
在下文中一共展示了operator.index方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bcd_decode
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def bcd_decode(value):
try:
# Far faster than my routine for scalars
return int('{:x}'.format(index(value)))
except TypeError as exc: # Might still be an array
try:
assert value.dtype.kind in 'iu'
except Exception:
raise exc
d = np.arange(value.itemsize * 2)
digits = (value[:, np.newaxis] >> d*4) & 0xf
if digits.max() > 9:
bad = value[(digits > 9).any(1)][0]
raise ValueError("invalid BCD encoded value {0}={1}."
.format(bad, hex(bad)))
return (digits * 10**d).sum(1)
示例2: check
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def check(self, stream):
"""Check that the CRC at the end of athe stream is correct.
Parameters
----------
stream : int or array of unsigned int
For an integer, the value is the stream to check the CRC for.
For arrays, the dimension is treated as the index into the bits.
A single stream would thus be of type `bool`. Unsigned integers
represent multiple streams. E.g., for a 64-track Mark 4 header,
the stream would be an array of ``np.uint64`` words.
Returns
-------
ok : bool
`True` if the calculated CRC is all zero (which should be the
case if the CRC at the end of the stream is correct).
"""
return self._crc(stream) == 0
示例3: test_same_kind_index_casting
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def test_same_kind_index_casting(self):
# Indexes should be cast with same-kind and not safe, even if that
# is somewhat unsafe. So test various different code paths.
index = np.arange(5)
u_index = index.astype(np.uintp)
arr = np.arange(10)
assert_array_equal(arr[index], arr[u_index])
arr[u_index] = np.arange(5)
assert_array_equal(arr, np.arange(10))
arr = np.arange(10).reshape(5, 2)
assert_array_equal(arr[index], arr[u_index])
arr[u_index] = np.arange(5)[:,None]
assert_array_equal(arr, np.arange(5)[:,None].repeat(2, axis=1))
arr = np.arange(25).reshape(5, 5)
assert_array_equal(arr[u_index, u_index], arr[index, index])
示例4: test_unaligned
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def test_unaligned(self):
v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7]
d = v.view(np.dtype("S8"))
# unaligned source
x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7]
x = x.view(np.dtype("S8"))
x[...] = np.array("b" * 8, dtype="S")
b = np.arange(d.size)
#trivial
assert_equal(d[b], d)
d[b] = x
# nontrivial
# unaligned index array
b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)]
b = b.view(np.intp)[:d.size]
b[...] = np.arange(d.size)
assert_equal(d[b.astype(np.int16)], d)
d[b.astype(np.int16)] = x
# boolean
d[b % 2 == 0]
d[b % 2 == 0] = x[::2]
示例5: test_broken_sequence_not_nd_index
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def test_broken_sequence_not_nd_index(self):
# See gh-5063:
# If we have an object which claims to be a sequence, but fails
# on item getting, this should not be converted to an nd-index (tuple)
# If this object happens to be a valid index otherwise, it should work
# This object here is very dubious and probably bad though:
class SequenceLike(object):
def __index__(self):
return 0
def __len__(self):
return 1
def __getitem__(self, item):
raise IndexError('Not possible')
arr = np.arange(10)
assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
# also test that field indexing does not segfault
# for a similar reason, by indexing a structured array
arr = np.zeros((1,), dtype=[('f1', 'i8'), ('f2', 'i8')])
assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])
示例6: test_boolean_index_cast_assign
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def test_boolean_index_cast_assign(self):
# Setup the boolean index and float arrays.
shape = (8, 63)
bool_index = np.zeros(shape).astype(bool)
bool_index[0, 1] = True
zero_array = np.zeros(shape)
# Assigning float is fine.
zero_array[bool_index] = np.array([1])
assert_equal(zero_array[0, 1], 1)
# Fancy indexing works, although we get a cast warning.
assert_warns(np.ComplexWarning,
zero_array.__setitem__, ([0], [1]), np.array([2 + 1j]))
assert_equal(zero_array[0, 1], 2) # No complex part
# Cast complex to float, throwing away the imaginary portion.
assert_warns(np.ComplexWarning,
zero_array.__setitem__, bool_index, np.array([1j]))
assert_equal(zero_array[0, 1], 0)
示例7: _check_multi_index
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def _check_multi_index(self, arr, index):
"""Check a multi index item getting and simple setting.
Parameters
----------
arr : ndarray
Array to be indexed, must be a reshaped arange.
index : tuple of indexing objects
Index being tested.
"""
# Test item getting
try:
mimic_get, no_copy = self._get_multi_index(arr, index)
except Exception as e:
if HAS_REFCOUNT:
prev_refcount = sys.getrefcount(arr)
assert_raises(type(e), arr.__getitem__, index)
assert_raises(type(e), arr.__setitem__, index, 0)
if HAS_REFCOUNT:
assert_equal(prev_refcount, sys.getrefcount(arr))
return
self._compare_index_result(arr, index, mimic_get, no_copy)
示例8: _check_single_index
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def _check_single_index(self, arr, index):
"""Check a single index item getting and simple setting.
Parameters
----------
arr : ndarray
Array to be indexed, must be an arange.
index : indexing object
Index being tested. Must be a single index and not a tuple
of indexing objects (see also `_check_multi_index`).
"""
try:
mimic_get, no_copy = self._get_multi_index(arr, (index,))
except Exception as e:
if HAS_REFCOUNT:
prev_refcount = sys.getrefcount(arr)
assert_raises(type(e), arr.__getitem__, index)
assert_raises(type(e), arr.__setitem__, index, 0)
if HAS_REFCOUNT:
assert_equal(prev_refcount, sys.getrefcount(arr))
return
self._compare_index_result(arr, index, mimic_get, no_copy)
示例9: hash_dataframe_on
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def hash_dataframe_on(df, on, size, level=None):
if on is None:
idx = df.index
if level is not None:
idx = idx.to_frame(False)[level]
hashed_label = pd.util.hash_pandas_object(idx, categorize=False)
elif callable(on):
# todo optimization can be added, if ``on`` is a numpy ufunc or sth can be vectorized
hashed_label = pd.util.hash_pandas_object(df.index.map(on), categorize=False)
else:
if isinstance(on, list):
to_concat = []
for v in on:
if isinstance(v, pd.Series):
to_concat.append(v)
else:
to_concat.append(df[v])
data = pd.concat(to_concat, axis=1)
else:
data = df[on]
hashed_label = pd.util.hash_pandas_object(data, index=False, categorize=False)
idx_to_grouped = df.index.groupby(hashed_label % size)
return [idx_to_grouped.get(i, pd.Index([])).unique() for i in range(size)]
示例10: build_split_idx_to_origin_idx
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def build_split_idx_to_origin_idx(splits, increase=True):
# splits' len is equal to the original chunk size on a specified axis,
# splits is sth like [[(0, True, 2, True), (2, False, 3, True)]]
# which means there is one input chunk, and will be split into 2 out chunks
# in this function, we want to build a new dict from the out chunk index to
# the original chunk index and the inner position, like {0: (0, 0), 1: (0, 1)}
if increase is False:
splits = list(reversed(splits))
out_idx = itertools.count(0)
res = dict()
for origin_idx, _ in enumerate(splits):
for pos in range(len(splits[origin_idx])):
if increase is False:
o_idx = len(splits) - origin_idx - 1
else:
o_idx = origin_idx
res[next(out_idx)] = o_idx, pos
return res
示例11: build_series
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def build_series(series_obj, fill_value=1, size=1):
empty_series = build_empty_series(series_obj.dtype, index=series_obj.index_value.to_pandas()[:0])
record = _generate_value(series_obj.dtype, fill_value)
if isinstance(empty_series.index, pd.MultiIndex):
index = tuple(_generate_value(level.dtype, fill_value) for level in empty_series.index.levels)
empty_series.loc[index, ] = record
else:
if isinstance(empty_series.index.dtype, pd.CategoricalDtype):
index = None
else:
index = _generate_value(empty_series.index.dtype, fill_value)
empty_series.loc[index] = record
empty_series = pd.concat([empty_series] * size)
# make sure dtype correct for MultiIndex
empty_series = empty_series.astype(series_obj.dtype, copy=False)
return empty_series
示例12: build_concatenated_rows_frame
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def build_concatenated_rows_frame(df):
from ..core import OutputType
from .merge.concat import DataFrameConcat
# When the df isn't splitted along the column axis, return the df directly.
if df.chunk_shape[1] == 1:
return df
columns = concat_index_value([df.cix[0, idx].columns_value for idx in range(df.chunk_shape[1])],
store_data=True)
columns_size = columns.to_pandas().size
out_chunks = []
for idx in range(df.chunk_shape[0]):
out_chunk = DataFrameConcat(axis=1, output_types=[OutputType.dataframe]).new_chunk(
[df.cix[idx, k] for k in range(df.chunk_shape[1])], index=(idx, 0),
shape=(df.cix[idx, 0].shape[0], columns_size), dtypes=df.dtypes,
index_value=df.cix[idx, 0].index_value, columns_value=columns)
out_chunks.append(out_chunk)
return DataFrameConcat(axis=1, output_types=[OutputType.dataframe]).new_dataframe(
[df], chunks=out_chunks, nsplits=((chunk.shape[0] for chunk in out_chunks), (df.shape[1],)),
shape=df.shape, dtypes=df.dtypes,
index_value=df.index_value, columns_value=df.columns_value)
示例13: infer_index_value
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def infer_index_value(left_index_value, right_index_value):
from .core import IndexValue
if isinstance(left_index_value.value, IndexValue.RangeIndex) and \
isinstance(right_index_value.value, IndexValue.RangeIndex):
if left_index_value.value.slice == right_index_value.value.slice:
return left_index_value
return parse_index(pd.Int64Index([]), left_index_value, right_index_value)
# when left index and right index is identical, and both of them are elements unique,
# we can infer that the out index should be identical also
if left_index_value.is_unique and right_index_value.is_unique and \
left_index_value.key == right_index_value.key:
return left_index_value
left_index = left_index_value.to_pandas()
right_index = right_index_value.to_pandas()
out_index = pd.Index([], dtype=find_common_type([left_index.dtype, right_index.dtype]))
return parse_index(out_index, left_index_value, right_index_value)
示例14: validate_axis
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def validate_axis(axis, tileable=None):
if axis == 'index':
axis = 0
elif axis == 'columns':
axis = 1
illegal = False
try:
axis = operator.index(axis)
if axis < 0 or (tileable is not None and axis >= tileable.ndim):
illegal = True
except TypeError:
illegal = True
if illegal:
raise ValueError('No axis named {} for '
'object type {}'.format(axis, type(tileable)))
return axis
示例15: __index__
# 需要导入模块: import operator [as 别名]
# 或者: from operator import index [as 别名]
def __index__(self):
return operator.index(self.__wrapped__)