本文整理汇总了Python中toolz.flip函数的典型用法代码示例。如果您正苦于以下问题:Python flip函数的具体用法?Python flip怎么用?Python flip使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了flip函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute_string_group_by_find_in_set
def execute_string_group_by_find_in_set(op, needle, haystack, **kwargs):
# `list` could contain series, series groupbys, or scalars
# mixing series and series groupbys is not allowed
series_in_haystack = [
type(piece)
for piece in haystack
if isinstance(piece, (pd.Series, SeriesGroupBy))
]
if not series_in_haystack:
return ibis.util.safe_index(haystack, needle)
try:
collection_type, = frozenset(map(type, series_in_haystack))
except ValueError:
raise ValueError('Mixing Series and SeriesGroupBy is not allowed')
pieces = haystack_to_series_of_lists(
[getattr(piece, 'obj', piece) for piece in haystack]
)
result = pieces.map(toolz.flip(ibis.util.safe_index)(needle))
if issubclass(collection_type, pd.Series):
return result
assert issubclass(collection_type, SeriesGroupBy)
return result.groupby(
toolz.first(
piece.grouper.groupings
for piece in haystack
if hasattr(piece, 'grouper')
)
)
示例2: alias
def alias(attr_name):
"""Make a fixture attribute an alias of another fixture's attribute by
default.
Parameters
----------
attr_name : str
The name of the attribute to alias.
Returns
-------
p : classproperty
A class property that does the property aliasing.
Examples
--------
>>> class C(object):
... attr = 1
...
>>> class D(C):
... attr_alias = alias('attr')
...
>>> D.attr
1
>>> D.attr_alias
1
>>> class E(D):
... attr_alias = 2
...
>>> E.attr
1
>>> E.attr_alias
2
"""
return classproperty(flip(getattr, attr_name))
示例3: foldr
def foldr(f, seq, default=_no_default):
"""Fold a function over a sequence with right associativity.
Parameters
----------
f : callable[any, any]
The function to reduce the sequence with.
The first argument will be the element of the sequence; the second
argument will be the accumulator.
seq : iterable[any]
The sequence to reduce.
default : any, optional
The starting value to reduce with. If not provided, the sequence
cannot be empty, and the last value of the sequence will be used.
Returns
-------
folded : any
The folded value.
Notes
-----
This functions works by reducing the list in a right associative way.
For example, imagine we are folding with ``operator.add`` or ``+``:
.. code-block:: python
foldr(add, seq) -> seq[0] + (seq[1] + (seq[2] + (...seq[-1], default)))
In the more general case with an arbitrary function, ``foldr`` will expand
like so:
.. code-block:: python
foldr(f, seq) -> f(seq[0], f(seq[1], f(seq[2], ...f(seq[-1], default))))
For a more in depth discussion of left and right folds, see:
`https://en.wikipedia.org/wiki/Fold_(higher-order_function)`_
The images in that page are very good for showing the differences between
``foldr`` and ``foldl`` (``reduce``).
.. note::
For performance reasons is is best to pass a strict (non-lazy) sequence,
for example, a list.
See Also
--------
:func:`functools.reduce`
:func:`sum`
"""
return reduce(
flip(f),
reversed(seq),
*(default,) if default is not _no_default else ()
)
示例4: nearest_working_datetime_range
def nearest_working_datetime_range(dt_range, availability={}):
"""
Nearest working datetime_range by datetime_range.
"""
a = defaulitize_availability(availability)
start_date = dt_range[0].date()
if not is_date_available(start_date, a):
return None
tomorrow_available = is_date_available(tomorrow(start_date), a)
working_dt_ranges = working_datetime_ranges_of_date(
start_date,
a['special_working_hours'], a['week_working_hours'],
merge_tomorrow=tomorrow_available)
is_near = partial(flip(end_after_or_eq), dt_range)
return first_match(is_near, working_dt_ranges)
示例5: stack
def stack(*imgs, **kwargs):
"""Combine images together, overlaying later images onto earlier ones.
Parameters
----------
imgs : iterable of Image
The images to combine.
how : str, optional
The compositing operator to combine pixels. Default is `'over'`.
"""
if not imgs:
raise ValueError("No images passed in")
for i in imgs:
if not isinstance(i, Image):
raise TypeError("Expected `Image`, got: `{0}`".format(type(i)))
op = composite_op_lookup[kwargs.get('how', 'over')]
if len(imgs) == 1:
return imgs[0]
imgs = xr.align(*imgs, copy=False, join='outer')
out = tz.reduce(tz.flip(op), [i.data for i in imgs])
return Image(out, coords=imgs[0].coords, dims=imgs[0].dims)
示例6: complement
from zipline.utils.numpy_utils import repeat_last_axis
AD_FIELD_NAME = 'asof_date'
TS_FIELD_NAME = 'timestamp'
SID_FIELD_NAME = 'sid'
valid_deltas_node_types = (
bz.expr.Field,
bz.expr.ReLabel,
bz.expr.Symbol,
)
traversable_nodes = (
bz.expr.Field,
bz.expr.Label,
)
is_invalid_deltas_node = complement(flip(isinstance, valid_deltas_node_types))
getname = op.attrgetter('__name__')
class _ExprRepr(object):
"""Box for repring expressions with the str of the expression.
Parameters
----------
expr : Expr
The expression to box for repring.
"""
__slots__ = 'expr',
def __init__(self, expr):
self.expr = expr
示例7: dtype
from toolz import flip
uint8_dtype = dtype("uint8")
bool_dtype = dtype("bool")
int64_dtype = dtype("int64")
float32_dtype = dtype("float32")
float64_dtype = dtype("float64")
complex128_dtype = dtype("complex128")
datetime64D_dtype = dtype("datetime64[D]")
datetime64ns_dtype = dtype("datetime64[ns]")
make_datetime64ns = flip(datetime64, "ns")
make_datetime64D = flip(datetime64, "D")
NaTmap = {dtype("datetime64[%s]" % unit): datetime64("NaT", unit) for unit in ("ns", "us", "ms", "s", "m", "D")}
NaT_for_dtype = NaTmap.__getitem__
NaTns = NaT_for_dtype(datetime64ns_dtype)
NaTD = NaT_for_dtype(datetime64D_dtype)
_FILLVALUE_DEFAULTS = {bool_dtype: False, float32_dtype: nan, float64_dtype: nan, datetime64ns_dtype: NaTns}
class NoDefaultMissingValue(Exception):
pass
示例8: dtype
from toolz import flip
uint8_dtype = dtype('uint8')
bool_dtype = dtype('bool')
int64_dtype = dtype('int64')
float32_dtype = dtype('float32')
float64_dtype = dtype('float64')
complex128_dtype = dtype('complex128')
datetime64D_dtype = dtype('datetime64[D]')
datetime64ns_dtype = dtype('datetime64[ns]')
make_datetime64ns = flip(datetime64, 'ns')
make_datetime64D = flip(datetime64, 'D')
NaTmap = {
dtype('datetime64[%s]' % unit): datetime64('NaT', unit)
for unit in ('ns', 'us', 'ms', 's', 'm', 'D')
}
NaT_for_dtype = NaTmap.__getitem__
NaTns = NaT_for_dtype(datetime64ns_dtype)
NaTD = NaT_for_dtype(datetime64D_dtype)
_FILLVALUE_DEFAULTS = {
bool_dtype: False,
float32_dtype: nan,
float64_dtype: nan,
示例9: _expected_data
def _expected_data(self):
sids = 0, 1, 2
modifier = {
'low': 0,
'open': 1,
'close': 2,
'high': 3,
'volume': 0,
}
pricing = [
np.hstack((
np.arange(252, dtype='float64')[:, np.newaxis] +
1 +
sid * 10000 +
modifier[column] * 1000
for sid in sorted(sids)
))
for column in self.columns
]
# There are two dividends and 1 split for each company.
def dividend_adjustment(sid, which):
"""The dividends occur at indices 252 // 4 and 3 * 252 / 4
with a cash amount of sid + 1 / 10 and sid + 2 / 10
"""
if which == 'first':
idx = 252 // 4
else:
idx = 3 * 252 // 4
return {
idx: [Float64Multiply(
first_row=0,
last_row=idx,
first_col=sid,
last_col=sid,
value=float(
1 -
((sid + 1 + (which == 'second')) / 10) /
(idx - 1 + sid * 10000 + 2000)
),
)],
}
def split_adjustment(sid, volume):
"""The splits occur at index 252 // 2 with a ratio of (sid + 1):1
"""
idx = 252 // 2
return {
idx: [Float64Multiply(
first_row=0,
last_row=idx,
first_col=sid,
last_col=sid,
value=(identity if volume else op.truediv(1))(sid + 2),
)],
}
merge_adjustments = merge_with(flip(sum, []))
adjustments = [
# ohlc
merge_adjustments(
*tuple(dividend_adjustment(sid, 'first') for sid in sids) +
tuple(dividend_adjustment(sid, 'second') for sid in sids) +
tuple(split_adjustment(sid, volume=False) for sid in sids)
)
] * (len(self.columns) - 1) + [
# volume
merge_adjustments(
split_adjustment(sid, volume=True) for sid in sids
),
]
return pricing, adjustments
示例10: working_hours_to_datetime_ranges
def working_hours_to_datetime_ranges(d, working_hours):
"""
Convert working_hours to datetime_ranges on specific date.
"""
partial_by_time_range = partial(flip(by_time_range), d)
return map(partial_by_time_range, working_hours)
示例11: contains_dt_range_in_wh_of_date
def contains_dt_range_in_wh_of_date(d, merge_tomorrow=True):
working_dt_ranges = working_datetime_ranges_of_date(
d, a['special_working_hours'], a['week_working_hours'],
merge_tomorrow=merge_tomorrow)
return any_match(partial(flip(contains), dt_range), working_dt_ranges)
示例12: is_a
def is_a(type_):
"""More curryable version of isinstance."""
return flip(isinstance, type_)