code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def index_drop_duplicates(index, keep="first", method="auto"):
"""
Return Index with duplicate values removed.
Parameters
----------
keep : {'first', 'last', ``False``}, default 'first'
- 'first' : Drop duplicates except for the first occurrence.
- 'last' : Drop duplicates except fo... |
Return Index with duplicate values removed.
Parameters
----------
keep : {'first', 'last', ``False``}, default 'first'
- 'first' : Drop duplicates except for the first occurrence.
- 'last' : Drop duplicates except for the last occurrence.
- ``False`` : Drop all duplicates.
... | index_drop_duplicates | python | mars-project/mars | mars/dataframe/base/drop_duplicates.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/drop_duplicates.py | Apache-2.0 |
def df_duplicated(df, subset=None, keep="first", method="auto"):
"""
Return boolean Series denoting duplicate rows.
Considering certain columns is optional.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplica... |
Return boolean Series denoting duplicate rows.
Considering certain columns is optional.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns.
keep : {'first', 'la... | df_duplicated | python | mars-project/mars | mars/dataframe/base/duplicated.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/duplicated.py | Apache-2.0 |
def series_duplicated(series, keep="first", method="auto"):
"""
Indicate duplicate Series values.
Duplicated values are indicated as ``True`` values in the resulting
Series. Either all duplicates, all except the first or all except the
last occurrence of duplicates can be indicated.
Parameters... |
Indicate duplicate Series values.
Duplicated values are indicated as ``True`` values in the resulting
Series. Either all duplicates, all except the first or all except the
last occurrence of duplicates can be indicated.
Parameters
----------
keep : {'first', 'last', False}, default 'first... | series_duplicated | python | mars-project/mars | mars/dataframe/base/duplicated.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/duplicated.py | Apache-2.0 |
def mars_eval(
expr,
parser="mars",
engine=None,
local_dict=None,
global_dict=None,
resolvers=(),
level=0,
target=None,
inplace=False,
):
"""
Evaluate a Python expression as a string using various backends.
The following arithmetic operations are supported: ``+``, ``-``... |
Evaluate a Python expression as a string using various backends.
The following arithmetic operations are supported: ``+``, ``-``, ``*``,
``/``, ``**``, ``%``, ``//`` (python engine only) along with the following
boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not).
Additionally, the ``'pa... | mars_eval | python | mars-project/mars | mars/dataframe/base/eval.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/eval.py | Apache-2.0 |
def df_eval(df, expr, inplace=False, **kwargs):
"""
Evaluate a string describing operations on DataFrame columns.
Operates on columns only, not specific rows or elements. This allows
`eval` to run arbitrary code, which can make you vulnerable to code
injection if you pass user input to this functi... |
Evaluate a string describing operations on DataFrame columns.
Operates on columns only, not specific rows or elements. This allows
`eval` to run arbitrary code, which can make you vulnerable to code
injection if you pass user input to this function.
Parameters
----------
expr : str
... | df_eval | python | mars-project/mars | mars/dataframe/base/eval.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/eval.py | Apache-2.0 |
def df_query(df, expr, inplace=False, **kwargs):
"""
Query the columns of a DataFrame with a boolean expression.
Parameters
----------
expr : str
The query string to evaluate.
You can refer to variables
in the environment by prefixing them with an '@' character like
... |
Query the columns of a DataFrame with a boolean expression.
Parameters
----------
expr : str
The query string to evaluate.
You can refer to variables
in the environment by prefixing them with an '@' character like
``@a + b``.
You can refer to column names that... | df_query | python | mars-project/mars | mars/dataframe/base/eval.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/eval.py | Apache-2.0 |
def series_isin(elements, values):
"""
Whether elements in Series are contained in `values`.
Return a boolean Series showing whether each element in the Series
matches an element in the passed sequence of `values` exactly.
Parameters
----------
values : set or list-like
The sequenc... |
Whether elements in Series are contained in `values`.
Return a boolean Series showing whether each element in the Series
matches an element in the passed sequence of `values` exactly.
Parameters
----------
values : set or list-like
The sequence of values to test. Passing in a single s... | series_isin | python | mars-project/mars | mars/dataframe/base/isin.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/isin.py | Apache-2.0 |
def df_isin(df, values):
"""
Whether each element in the DataFrame is contained in values.
Parameters
----------
values : iterable, Series, DataFrame or dict
The result will only be true at a location if all the
labels match. If `values` is a Series, that's the index. If
`va... |
Whether each element in the DataFrame is contained in values.
Parameters
----------
values : iterable, Series, DataFrame or dict
The result will only be true at a location if all the
labels match. If `values` is a Series, that's the index. If
`values` is a dict, the keys must b... | df_isin | python | mars-project/mars | mars/dataframe/base/isin.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/isin.py | Apache-2.0 |
def series_map(
series, arg, na_action=None, dtype=None, memory_scale=None, skip_infer=False
):
"""
Map values of Series according to input correspondence.
Used for substituting each value in a Series with another value,
that may be derived from a function, a ``dict`` or
a :class:`Series`.
... |
Map values of Series according to input correspondence.
Used for substituting each value in a Series with another value,
that may be derived from a function, a ``dict`` or
a :class:`Series`.
Parameters
----------
arg : function, collections.abc.Mapping subclass or Series
Mapping c... | series_map | python | mars-project/mars | mars/dataframe/base/map.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/map.py | Apache-2.0 |
def index_map(
idx, mapper, na_action=None, dtype=None, memory_scale=None, skip_infer=False
):
"""
Map values using input correspondence (a dict, Series, or function).
Parameters
----------
mapper : function, dict, or Series
Mapping correspondence.
na_action : {None, 'ignore'}
... |
Map values using input correspondence (a dict, Series, or function).
Parameters
----------
mapper : function, dict, or Series
Mapping correspondence.
na_action : {None, 'ignore'}
If 'ignore', propagate NA values, without passing them to the
mapping correspondence.
dtype... | index_map | python | mars-project/mars | mars/dataframe/base/map.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/map.py | Apache-2.0 |
def map_chunk(df_or_series, func, args=(), kwargs=None, skip_infer=False, **kw):
"""
Apply function to each chunk.
Parameters
----------
func : function
Function to apply to each chunk.
args : tuple
Positional arguments to pass to func in addition to the array/series.
kwargs... |
Apply function to each chunk.
Parameters
----------
func : function
Function to apply to each chunk.
args : tuple
Positional arguments to pass to func in addition to the array/series.
kwargs: Dict
Additional keyword arguments to pass as keywords arguments to func.
s... | map_chunk | python | mars-project/mars | mars/dataframe/base/map_chunk.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/map_chunk.py | Apache-2.0 |
def melt(
frame,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level=None,
):
"""
Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.
This function is useful to massage a DataFrame into a format where one
or more columns are ... |
Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.
This function is useful to massage a DataFrame into a format where one
or more columns are identifier variables (`id_vars`), while all other
columns, considered measured variables (`value_vars`), are "unpivoted" to
t... | melt | python | mars-project/mars | mars/dataframe/base/melt.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/melt.py | Apache-2.0 |
def _adapt_index(self, input_index, index=0):
"""
When ``index=True`` is passed, an extra column will be prepended to the result series
Thus we need to update the index of initial chunk for returned dataframe chunks
"""
if not self.index or index != 0:
return input_in... |
When ``index=True`` is passed, an extra column will be prepended to the result series
Thus we need to update the index of initial chunk for returned dataframe chunks
| _adapt_index | python | mars-project/mars | mars/dataframe/base/memory_usage.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/memory_usage.py | Apache-2.0 |
def _adapt_nsplits(self, input_nsplit):
"""
When ``index=True`` is passed, the size of returned series is one element larger
than the number of columns, which affects ``nsplits``.
"""
if not self.index:
return (input_nsplit[-1],)
nsplits_list = list(input_nspl... |
When ``index=True`` is passed, the size of returned series is one element larger
than the number of columns, which affects ``nsplits``.
| _adapt_nsplits | python | mars-project/mars | mars/dataframe/base/memory_usage.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/memory_usage.py | Apache-2.0 |
def _tile_single(cls, op: "DataFrameMemoryUsage"):
"""
Tile when input data has only one chunk on rows
"""
df_or_series = op.inputs[0]
output = op.outputs[0]
chunks = []
for c in df_or_series.chunks:
new_op = op.copy().reset_key()
if c.ndi... |
Tile when input data has only one chunk on rows
| _tile_single | python | mars-project/mars | mars/dataframe/base/memory_usage.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/memory_usage.py | Apache-2.0 |
def qcut(x, q, labels=None, retbins=False, precision=3, duplicate="raise"):
"""
Quantile-based discretization function.
Discretize variable into equal-sized buckets based on rank or based
on sample quantiles. For example 1000 values for 10 quantiles would
produce a Categorical object indicating qua... |
Quantile-based discretization function.
Discretize variable into equal-sized buckets based on rank or based
on sample quantiles. For example 1000 values for 10 quantiles would
produce a Categorical object indicating quantile membership for each data point.
Parameters
----------
x : 1d ten... | qcut | python | mars-project/mars | mars/dataframe/base/qcut.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/qcut.py | Apache-2.0 |
def rebalance(
df_or_series, factor=None, axis=0, num_partitions=None, reassign_worker=True
):
"""
Make Data more balanced across entire cluster.
Parameters
----------
factor : float
Specified so that number of chunks after balance is
total CPU count of cluster * factor.
axi... |
Make Data more balanced across entire cluster.
Parameters
----------
factor : float
Specified so that number of chunks after balance is
total CPU count of cluster * factor.
axis : int
The axis to rebalance.
num_partitions : int
Specified so the number of chunks ... | rebalance | python | mars-project/mars | mars/dataframe/base/rebalance.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/rebalance.py | Apache-2.0 |
def select_dtypes(df, include=None, exclude=None):
"""
Return a subset of the DataFrame's columns based on the column dtypes.
Parameters
----------
include, exclude : scalar or list-like
A selection of dtypes or strings to be included/excluded. At least
one of these parameters must ... |
Return a subset of the DataFrame's columns based on the column dtypes.
Parameters
----------
include, exclude : scalar or list-like
A selection of dtypes or strings to be included/excluded. At least
one of these parameters must be supplied.
Returns
-------
DataFrame
... | select_dtypes | python | mars-project/mars | mars/dataframe/base/select_dtypes.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/select_dtypes.py | Apache-2.0 |
def shift(df_or_series, periods=1, freq=None, axis=0, fill_value=None):
"""
Shift index by desired number of periods with an optional time `freq`.
When `freq` is not passed, shift the index without realigning the data.
If `freq` is passed (in this case, the index must be date or datetime,
or it wil... |
Shift index by desired number of periods with an optional time `freq`.
When `freq` is not passed, shift the index without realigning the data.
If `freq` is passed (in this case, the index must be date or datetime,
or it will raise a `NotImplementedError`), the index will be
increased using the per... | shift | python | mars-project/mars | mars/dataframe/base/shift.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/shift.py | Apache-2.0 |
def df_transform(df, func, axis=0, *args, dtypes=None, skip_infer=False, **kwargs):
"""
Call ``func`` on self producing a DataFrame with transformed values.
Produced DataFrame will have same axis length as self.
Parameters
----------
func : function, str, list or dict
Function to use f... |
Call ``func`` on self producing a DataFrame with transformed values.
Produced DataFrame will have same axis length as self.
Parameters
----------
func : function, str, list or dict
Function to use for transforming the data. If a function, must either
work when passed a DataFrame o... | df_transform | python | mars-project/mars | mars/dataframe/base/transform.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/transform.py | Apache-2.0 |
def series_transform(
series,
func,
convert_dtype=True,
axis=0,
*args,
skip_infer=False,
dtype=None,
**kwargs
):
"""
Call ``func`` on self producing a Series with transformed values.
Produced Series will have same axis length as self.
Parameters
----------
func ... |
Call ``func`` on self producing a Series with transformed values.
Produced Series will have same axis length as self.
Parameters
----------
func : function, str, list or dict
Function to use for transforming the data. If a function, must either
work when passed a Series or when passed to ... | series_transform | python | mars-project/mars | mars/dataframe/base/transform.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/transform.py | Apache-2.0 |
def value_counts(
series,
normalize=False,
sort=True,
ascending=False,
bins=None,
dropna=True,
method="auto",
):
"""
Return a Series containing counts of unique values.
The resulting object will be in descending order so that the
first element is the most frequently-occurrin... |
Return a Series containing counts of unique values.
The resulting object will be in descending order so that the
first element is the most frequently-occurring element.
Excludes NA values by default.
Parameters
----------
normalize : bool, default False
If True then the object ret... | value_counts | python | mars-project/mars | mars/dataframe/base/value_counts.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/base/value_counts.py | Apache-2.0 |
def to_ray_dataset(df, num_shards: int = None):
"""Create a Ray Dataset from Mars DataFrame
Args:
df (mars.dataframe.Dataframe): the Mars DataFrame
num_shards (int, optional): the number of shards that will be created
for the Ray Dataset. Defaults to None.
If num_shards ... | Create a Ray Dataset from Mars DataFrame
Args:
df (mars.dataframe.Dataframe): the Mars DataFrame
num_shards (int, optional): the number of shards that will be created
for the Ray Dataset. Defaults to None.
If num_shards is None, chunks will be grouped by nodes where they lie... | to_ray_dataset | python | mars-project/mars | mars/dataframe/contrib/raydataset/dataset.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/contrib/raydataset/dataset.py | Apache-2.0 |
def __init__(self, shard_id: int, obj_refs: "ray.ObjectRef"):
"""Iterable batch holding a list of ray.ObjectRefs.
Args:
shard_id (int): id of the shard
prefix (str): prefix name of the batch
obj_refs (List[ray.ObjectRefs]): list of ray.ObjectRefs
"""
... | Iterable batch holding a list of ray.ObjectRefs.
Args:
shard_id (int): id of the shard
prefix (str): prefix name of the batch
obj_refs (List[ray.ObjectRefs]): list of ray.ObjectRefs
| __init__ | python | mars-project/mars | mars/dataframe/contrib/raydataset/mldataset.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/contrib/raydataset/mldataset.py | Apache-2.0 |
def _group_chunk_refs(
chunk_addr_refs: List[Tuple[Tuple, "ray.ObjectRef"]], num_shards: int
):
"""Group fetched ray.ObjectRefs into a dict for later use.
Args:
chunk_addr_refs (List[Tuple[Tuple, ray.ObjectRef]]): a list of tuples of
band & ray.ObjectRef of each chunk.
num_shard... | Group fetched ray.ObjectRefs into a dict for later use.
Args:
chunk_addr_refs (List[Tuple[Tuple, ray.ObjectRef]]): a list of tuples of
band & ray.ObjectRef of each chunk.
num_shards (int): the number of shards that will be created for the MLDataset.
Returns:
Dict[str, List[... | _group_chunk_refs | python | mars-project/mars | mars/dataframe/contrib/raydataset/mldataset.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/contrib/raydataset/mldataset.py | Apache-2.0 |
def to_ray_mldataset(df, num_shards: int = None):
"""Create a MLDataset from Mars DataFrame
Args:
df (mars.dataframe.Dataframe): the Mars DataFrame
num_shards (int, optional): the number of shards that will be created
for the MLDataset. Defaults to None.
If num_shards is... | Create a MLDataset from Mars DataFrame
Args:
df (mars.dataframe.Dataframe): the Mars DataFrame
num_shards (int, optional): the number of shards that will be created
for the MLDataset. Defaults to None.
If num_shards is None, chunks will be grouped by nodes where they lie.
... | to_ray_mldataset | python | mars-project/mars | mars/dataframe/contrib/raydataset/mldataset.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/contrib/raydataset/mldataset.py | Apache-2.0 |
def _infer_tz_from_endpoints(start, end, tz): # pragma: no cover
"""
If a timezone is not explicitly given via `tz`, see if one can
be inferred from the `start` and `end` endpoints. If more than one
of these inputs provides a timezone, require that they all agree.
Parameters
----------
st... |
If a timezone is not explicitly given via `tz`, see if one can
be inferred from the `start` and `end` endpoints. If more than one
of these inputs provides a timezone, require that they all agree.
Parameters
----------
start : Timestamp
end : Timestamp
tz : tzinfo or None
Returns
... | _infer_tz_from_endpoints | python | mars-project/mars | mars/dataframe/datasource/date_range.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/datasource/date_range.py | Apache-2.0 |
def _maybe_localize_point(
ts, is_none, is_not_none, freq, tz, ambiguous, nonexistent
): # pragma: no cover
"""
Localize a start or end Timestamp to the timezone of the corresponding
start or end Timestamp
Parameters
----------
ts : start or end Timestamp to potentially localize
is_non... |
Localize a start or end Timestamp to the timezone of the corresponding
start or end Timestamp
Parameters
----------
ts : start or end Timestamp to potentially localize
is_none : argument that should be None
is_not_none : argument that should not be None
freq : Tick, DateOffset, or None... | _maybe_localize_point | python | mars-project/mars | mars/dataframe/datasource/date_range.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/datasource/date_range.py | Apache-2.0 |
def read_parquet(
path,
engine: str = "auto",
columns: list = None,
groups_as_chunks: bool = False,
use_arrow_dtype: bool = None,
incremental_index: bool = False,
storage_options: dict = None,
memory_scale: int = None,
merge_small_files: bool = True,
merge_small_file_options: dic... |
Load a parquet object from the file path, returning a DataFrame.
Parameters
----------
path : str, path object or file-like object
Any valid string path is acceptable. The string could be a URL.
For file URLs, a host is expected. A local file could be:
``file://localhost/path/t... | read_parquet | python | mars-project/mars | mars/dataframe/datasource/read_parquet.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/datasource/read_parquet.py | Apache-2.0 |
def _update_key(self):
"""We can't direct generate token for mldataset when we use
ray client, so we use all mldataset's actor_id to generate
token.
"""
datas = []
for value in self._values_:
if isinstance(value, ray.util.data.MLDataset):
actor... | We can't direct generate token for mldataset when we use
ray client, so we use all mldataset's actor_id to generate
token.
| _update_key | python | mars-project/mars | mars/dataframe/datasource/read_raydataset.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/datasource/read_raydataset.py | Apache-2.0 |
def to_parquet(
df,
path,
engine="auto",
compression="snappy",
index=None,
partition_cols=None,
storage_options: dict = None,
**kwargs,
):
"""
Write a DataFrame to the binary parquet format, each chunk will be
written to a Parquet file.
Parameters
----------
path... |
Write a DataFrame to the binary parquet format, each chunk will be
written to a Parquet file.
Parameters
----------
path : str or file-like object
If path is a string with wildcard e.g. '/to/path/out-*.parquet',
`to_parquet` will try to write multiple files, for instance,
c... | to_parquet | python | mars-project/mars | mars/dataframe/datastore/to_parquet.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/datastore/to_parquet.py | Apache-2.0 |
def to_sql(
df,
name: str,
con,
schema=None,
if_exists: str = "fail",
index: bool = True,
index_label=None,
chunksize=None,
dtype=None,
method=None,
):
"""
Write records stored in a DataFrame to a SQL database.
Databases supported by SQLAlchemy [1]_ are supported. Ta... |
Write records stored in a DataFrame to a SQL database.
Databases supported by SQLAlchemy [1]_ are supported. Tables can be
newly created, appended to, or overwritten.
Parameters
----------
name : str
Name of SQL table.
con : sqlalchemy.engine.Engine or sqlite3.Connection
U... | to_sql | python | mars-project/mars | mars/dataframe/datastore/to_sql.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/datastore/to_sql.py | Apache-2.0 |
def agg(groupby, func=None, method="auto", combine_size=None, *args, **kwargs):
"""
Aggregate using one or more operations on grouped data.
Parameters
----------
groupby : Mars Groupby
Groupby data.
func : str or list-like
Aggregation functions.
method : {'auto', 'shuffle', ... |
Aggregate using one or more operations on grouped data.
Parameters
----------
groupby : Mars Groupby
Groupby data.
func : str or list-like
Aggregation functions.
method : {'auto', 'shuffle', 'tree'}, default 'auto'
'tree' method provide a better performance, 'shuffle' i... | agg | python | mars-project/mars | mars/dataframe/groupby/aggregation.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/aggregation.py | Apache-2.0 |
def groupby_apply(
groupby,
func,
*args,
output_type=None,
dtypes=None,
dtype=None,
name=None,
index=None,
skip_infer=None,
**kwargs,
):
"""
Apply function `func` group-wise and combine the results together.
The function passed to `apply` must take a dataframe as its... |
Apply function `func` group-wise and combine the results together.
The function passed to `apply` must take a dataframe as its first
argument and return a DataFrame, Series or scalar. `apply` will
then take care of combining the results back together into a single
dataframe or series. `apply` is t... | groupby_apply | python | mars-project/mars | mars/dataframe/groupby/apply.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/apply.py | Apache-2.0 |
def execute_map(cls, op, in_data: pd.DataFrame) -> Union[pd.DataFrame, pd.Series]:
"""
Map stage implement.
Parameters
-------
op : Any operand
DataFrame operand.
in_data : pd.DataFrame
Input dataframe.
Returns
-------
... |
Map stage implement.
Parameters
-------
op : Any operand
DataFrame operand.
in_data : pd.DataFrame
Input dataframe.
Returns
-------
The result of op map stage.
| execute_map | python | mars-project/mars | mars/dataframe/groupby/custom_aggregation.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/custom_aggregation.py | Apache-2.0 |
def execute_combine(
cls, op, in_data: pd.DataFrame
) -> Union[pd.DataFrame, pd.Series]:
"""
Combine stage implement.
Parameters
----------
op : Any operand
DataFrame operand.
in_data : pd.Dataframe
Input dataframe.
Returns
... |
Combine stage implement.
Parameters
----------
op : Any operand
DataFrame operand.
in_data : pd.Dataframe
Input dataframe.
Returns
-------
The result of op combine stage.
| execute_combine | python | mars-project/mars | mars/dataframe/groupby/custom_aggregation.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/custom_aggregation.py | Apache-2.0 |
def execute_agg(cls, op, in_data: pd.DataFrame) -> Union[pd.DataFrame, pd.Series]:
"""
Agg stage implement.
Parameters
----------
op : Any operand
DataFrame operand.
in_data : pd.Dataframe
Input dataframe.
Returns
-------
... |
Agg stage implement.
Parameters
----------
op : Any operand
DataFrame operand.
in_data : pd.Dataframe
Input dataframe.
Returns
-------
The result of op agg stage.
| execute_agg | python | mars-project/mars | mars/dataframe/groupby/custom_aggregation.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/custom_aggregation.py | Apache-2.0 |
def head(groupby, n=5):
"""
Return first n rows of each group.
Similar to ``.apply(lambda x: x.head(n))``, but it returns a subset of rows
from the original Series or DataFrame with original index and order preserved
(``as_index`` flag is ignored).
Does not work for negative values of `n`.
... |
Return first n rows of each group.
Similar to ``.apply(lambda x: x.head(n))``, but it returns a subset of rows
from the original Series or DataFrame with original index and order preserved
(``as_index`` flag is ignored).
Does not work for negative values of `n`.
Returns
-------
Serie... | head | python | mars-project/mars | mars/dataframe/groupby/head.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/head.py | Apache-2.0 |
def _get_level_indexes(
cls, op: DataFrameGroupByAgg, data: pd.DataFrame
) -> List[int]:
"""
When group by level, get the level index list.
Level can be int, level name, or sequence of such.
This function calculates the corresponding indexes.
Parameters
------... |
When group by level, get the level index list.
Level can be int, level name, or sequence of such.
This function calculates the corresponding indexes.
Parameters
----------
op
data
Returns
-------
| _get_level_indexes | python | mars-project/mars | mars/dataframe/groupby/nunique.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/nunique.py | Apache-2.0 |
def _get_selection_columns(cls, op: DataFrameGroupByAgg) -> Union[None, List]:
"""
Get groupby selection columns from op parameters.
If this returns None, it means all columns are required.
Parameters
----------
op
Returns
-------
"""
if ... |
Get groupby selection columns from op parameters.
If this returns None, it means all columns are required.
Parameters
----------
op
Returns
-------
| _get_selection_columns | python | mars-project/mars | mars/dataframe/groupby/nunique.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/nunique.py | Apache-2.0 |
def groupby_sample(
groupby,
n: Optional[int] = None,
frac: Optional[float] = None,
replace: bool = False,
weights: Union[Sequence, pd.Series, None] = None,
random_state: Optional[np.random.RandomState] = None,
errors: str = "ignore",
):
"""
Return a random sample of items from each ... |
Return a random sample of items from each group.
You can use `random_state` for reproducibility.
Parameters
----------
n : int, optional
Number of items to return for each group. Cannot be used with
`frac` and must be no larger than the smallest group unless
`replace` is T... | groupby_sample | python | mars-project/mars | mars/dataframe/groupby/sample.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/sample.py | Apache-2.0 |
def groupby_transform(
groupby,
f,
*args,
dtypes=None,
dtype=None,
name=None,
index=None,
output_types=None,
skip_infer=False,
**kwargs,
):
"""
Call function producing a like-indexed DataFrame on each group and
return a DataFrame having the same indexes as the origina... |
Call function producing a like-indexed DataFrame on each group and
return a DataFrame having the same indexes as the original object
filled with the transformed values
Parameters
----------
f : function
Function to apply to each group.
dtypes : Series, default None
Specify... | groupby_transform | python | mars-project/mars | mars/dataframe/groupby/transform.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/transform.py | Apache-2.0 |
def _tree_getitem(cls, op):
"""
DataFrame doesn't store the index value except RangeIndex or specify `store=True` in `parse_index`,
So we build a tree structure to avoid too much dependence for getitem node.
"""
out_series = op.outputs[0]
combine_size = options.combine_si... |
DataFrame doesn't store the index value except RangeIndex or specify `store=True` in `parse_index`,
So we build a tree structure to avoid too much dependence for getitem node.
| _tree_getitem | python | mars-project/mars | mars/dataframe/indexing/getitem.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/getitem.py | Apache-2.0 |
def df_insert(df, loc, column, value, allow_duplicates=False):
"""
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int
Insertion index. M... |
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int
Insertion index. Must verify 0 <= loc <= len(columns).
column : str, number, or hash... | df_insert | python | mars-project/mars | mars/dataframe/indexing/insert.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/insert.py | Apache-2.0 |
def df_rename(
df,
mapper=None,
index=None,
columns=None,
axis="index",
copy=True,
inplace=False,
level=None,
errors="ignore",
):
"""
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra ... |
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
Parameters
----------
mapper : dict-like or function
Dict-like or functions transformations to apply to
... | df_rename | python | mars-project/mars | mars/dataframe/indexing/rename.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py | Apache-2.0 |
def series_rename(
series,
index=None,
*,
axis="index",
copy=True,
inplace=False,
level=None,
errors="ignore"
):
"""
Alter Series index labels or name.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra label... |
Alter Series index labels or name.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
Alternatively, change ``Series.name`` with a scalar value.
Parameters
----------
axis : {0 or "inde... | series_rename | python | mars-project/mars | mars/dataframe/indexing/rename.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py | Apache-2.0 |
def index_rename(index, name, inplace=False):
"""
Alter Index or MultiIndex name.
Able to set new names without level. Defaults to returning new index.
Length of names must match number of levels in MultiIndex.
Parameters
----------
name : label or list of labels
Name(s) to set.
... |
Alter Index or MultiIndex name.
Able to set new names without level. Defaults to returning new index.
Length of names must match number of levels in MultiIndex.
Parameters
----------
name : label or list of labels
Name(s) to set.
inplace : bool, default False
Modifies the ... | index_rename | python | mars-project/mars | mars/dataframe/indexing/rename.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py | Apache-2.0 |
def index_set_names(index, names, level=None, inplace=False):
"""
Set Index or MultiIndex name.
Able to set new names partially and by level.
Parameters
----------
names : label or list of label
Name(s) to set.
level : int, label or list of int or label, optional
If the ind... |
Set Index or MultiIndex name.
Able to set new names partially and by level.
Parameters
----------
names : label or list of label
Name(s) to set.
level : int, label or list of int or label, optional
If the index is a MultiIndex, level(s) to set (None for all
levels). Ot... | index_set_names | python | mars-project/mars | mars/dataframe/indexing/rename.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py | Apache-2.0 |
def rename_axis(
df_or_series,
mapper=None,
index=None,
columns=None,
axis=0,
copy=True,
inplace=False,
):
"""
Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
... |
Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
index, columns : scalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to
... | rename_axis | python | mars-project/mars | mars/dataframe/indexing/rename_axis.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename_axis.py | Apache-2.0 |
def calc_columns_index(column_name, df):
"""
Calculate the chunk index on the axis 1 according to the selected column.
:param column_name: selected column name
:param df: input tiled DataFrame
:return: chunk index on the columns axis
"""
column_nsplits = df.nsplits[1]
# if has duplicate ... |
Calculate the chunk index on the axis 1 according to the selected column.
:param column_name: selected column name
:param df: input tiled DataFrame
:return: chunk index on the columns axis
| calc_columns_index | python | mars-project/mars | mars/dataframe/indexing/utils.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/utils.py | Apache-2.0 |
def convert_labels_into_positions(pandas_index, labels):
"""
Convert labels into positions
:param pandas_index: pandas Index
:param labels: labels
:return: positions
"""
result = []
for label in labels:
loc = pandas_index.get_loc(label)
if isinstance(loc, (int, np.intege... |
Convert labels into positions
:param pandas_index: pandas Index
:param labels: labels
:return: positions
| convert_labels_into_positions | python | mars-project/mars | mars/dataframe/indexing/utils.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/utils.py | Apache-2.0 |
def merge(
df: Union[DataFrame, Series],
right: Union[DataFrame, Series],
how: str = "inner",
on: str = None,
left_on: str = None,
right_on: str = None,
left_index: bool = False,
right_index: bool = False,
sort: bool = False,
suffixes: Tuple[Optional[str], Optional[str]] = ("_x",... |
Merge DataFrame or named Series objects with a database-style join.
A named Series object is treated as a DataFrame with a single named column.
The join is done on columns or indexes. If joining columns on
columns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes
on indexes o... | merge | python | mars-project/mars | mars/dataframe/merge/merge.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/merge/merge.py | Apache-2.0 |
def join(
df: Union[DataFrame, Series],
other: Union[DataFrame, Series],
on: str = None,
how: str = "left",
lsuffix: str = "",
rsuffix: str = "",
sort: bool = False,
method: str = None,
auto_merge: str = "both",
auto_merge_threshold: int = 8,
bloom_filter: Union[bool, Dict] =... |
Join columns of another DataFrame.
Join columns with `other` DataFrame either on index or on a key
column. Efficiently join multiple DataFrame objects by index at once by
passing a list.
Parameters
----------
other : DataFrame, Series, or list of DataFrame
Index should be similar ... | join | python | mars-project/mars | mars/dataframe/merge/merge.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/merge/merge.py | Apache-2.0 |
def df_dropna(
df, axis=0, how=no_default, thresh=no_default, subset=None, inplace=False
):
"""
Remove missing values.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index'... |
Remove missing values.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
Determine if rows or columns which contain missing values are
... | df_dropna | python | mars-project/mars | mars/dataframe/missing/dropna.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/dropna.py | Apache-2.0 |
def series_dropna(series, axis=0, inplace=False, how=None):
"""
Return a new Series with missing values removed.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index'}, default... |
Return a new Series with missing values removed.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index'}, default 0
There is only one axis to drop values from.
inplace ... | series_dropna | python | mars-project/mars | mars/dataframe/missing/dropna.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/dropna.py | Apache-2.0 |
def index_dropna(index, how="any"):
"""
Return Index without NA/NaN values.
Parameters
----------
how : {'any', 'all'}, default 'any'
If the Index is a MultiIndex, drop the value when any or all levels
are NaN.
Returns
-------
Index
"""
use_inf_as_na = options.d... |
Return Index without NA/NaN values.
Parameters
----------
how : {'any', 'all'}, default 'any'
If the Index is a MultiIndex, drop the value when any or all levels
are NaN.
Returns
-------
Index
| index_dropna | python | mars-project/mars | mars/dataframe/missing/dropna.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/dropna.py | Apache-2.0 |
def ffill(df, axis=None, inplace=False, limit=None, downcast=None):
"""
Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``.
Returns
-------
{klass} or None
Object with missing values filled or None if ``inplace=True``.
"""
return fillna(
df, method="ffill", axis=ax... |
Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``.
Returns
-------
{klass} or None
Object with missing values filled or None if ``inplace=True``.
| ffill | python | mars-project/mars | mars/dataframe/missing/fillna.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/fillna.py | Apache-2.0 |
def bfill(df, axis=None, inplace=False, limit=None, downcast=None):
"""
Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``.
Returns
-------
{klass} or None
Object with missing values filled or None if ``inplace=True``.
"""
return fillna(
df, method="bfill", axis=ax... |
Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``.
Returns
-------
{klass} or None
Object with missing values filled or None if ``inplace=True``.
| bfill | python | mars-project/mars | mars/dataframe/missing/fillna.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/fillna.py | Apache-2.0 |
def index_fillna(index, value=None, downcast=None):
"""
Fill NA/NaN values with the specified value.
Parameters
----------
value : scalar
Scalar value to use to fill holes (e.g. 0).
This value cannot be a list-likes.
downcast : dict, default is None
A dict of item->dtype... |
Fill NA/NaN values with the specified value.
Parameters
----------
value : scalar
Scalar value to use to fill holes (e.g. 0).
This value cannot be a list-likes.
downcast : dict, default is None
A dict of item->dtype of what to downcast if possible,
or the string 'in... | index_fillna | python | mars-project/mars | mars/dataframe/missing/fillna.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/fillna.py | Apache-2.0 |
def _generate_function_str(self, out_tileable):
"""
Generate python code from tileable DAG
"""
from ...tensor.arithmetic.core import TensorBinOp, TensorUnaryOp
from ...tensor.base import TensorWhere
from ...tensor.datasource import Scalar
from ..arithmetic.core im... |
Generate python code from tileable DAG
| _generate_function_str | python | mars-project/mars | mars/dataframe/reduction/core.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/reduction/core.py | Apache-2.0 |
def nunique_dataframe(df, axis=0, dropna=True, combine_size=None):
"""
Count distinct observations over requested axis.
Return Series with number of distinct observations. Can ignore NaN
values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use.... |
Count distinct observations over requested axis.
Return Series with number of distinct observations. Can ignore NaN
values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for
column-wise.
dr... | nunique_dataframe | python | mars-project/mars | mars/dataframe/reduction/nunique.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/reduction/nunique.py | Apache-2.0 |
def nunique_series(series, dropna=True, combine_size=None):
"""
Return number of unique elements in the object.
Excludes NA values by default.
Parameters
----------
dropna : bool, default True
Don't include NaN in the count.
combine_size : int, optional
The number of chunks... |
Return number of unique elements in the object.
Excludes NA values by default.
Parameters
----------
dropna : bool, default True
Don't include NaN in the count.
combine_size : int, optional
The number of chunks to combine.
Returns
-------
int
See Also
---... | nunique_series | python | mars-project/mars | mars/dataframe/reduction/nunique.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/reduction/nunique.py | Apache-2.0 |
def df_corrwith(df, other, axis=0, drop=False, method="pearson"):
"""
Compute pairwise correlation.
Pairwise correlation is computed between rows or columns of
DataFrame with rows or columns of Series or DataFrame. DataFrames
are first aligned along both axes before computing the
correlations.
... |
Compute pairwise correlation.
Pairwise correlation is computed between rows or columns of
DataFrame with rows or columns of Series or DataFrame. DataFrames
are first aligned along both axes before computing the
correlations.
Parameters
----------
other : DataFrame, Series
Obje... | df_corrwith | python | mars-project/mars | mars/dataframe/statistics/corr.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/statistics/corr.py | Apache-2.0 |
def quantile_series(series, q=0.5, interpolation="linear"):
"""
Return value at the given quantile.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
0 <= q <= 1, the quantile(s) to compute.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
... |
Return value at the given quantile.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
0 <= q <= 1, the quantile(s) to compute.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
This optional parameter specifies the interpolation method to... | quantile_series | python | mars-project/mars | mars/dataframe/statistics/quantile.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/statistics/quantile.py | Apache-2.0 |
def quantile_dataframe(df, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
"""
Return values at the given quantile over requested axis.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value between 0 <= q <= 1, the quantile(s) to compute.
axis : {0, ... |
Return values at the given quantile over requested axis.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value between 0 <= q <= 1, the quantile(s) to compute.
axis : {0, 1, 'index', 'columns'} (default 0)
Equals 0 or 'index' for row-wise, 1 or 'columns' f... | quantile_dataframe | python | mars-project/mars | mars/dataframe/statistics/quantile.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/statistics/quantile.py | Apache-2.0 |
def ewm(
obj,
com=None,
span=None,
halflife=None,
alpha=None,
min_periods=0,
adjust=True,
ignore_na=False,
axis=0,
):
r"""
Provide exponential weighted functions.
Parameters
----------
com : float, optional
Specify decay in terms of center of mass,
... |
Provide exponential weighted functions.
Parameters
----------
com : float, optional
Specify decay in terms of center of mass,
:math:`\alpha = 1 / (1 + com),\text{ for } com \geq 0`.
span : float, optional
Specify decay in terms of span,
:math:`\alpha = 2 / (span + 1... | ewm | python | mars-project/mars | mars/dataframe/window/ewm/core.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/window/ewm/core.py | Apache-2.0 |
def expanding(obj, min_periods=1, center=False, axis=0):
"""
Provide expanding transformations.
Parameters
----------
min_periods : int, default 1
Minimum number of observations in window required to have a value
(otherwise result is NA).
center : bool, default False
Set the labels ... |
Provide expanding transformations.
Parameters
----------
min_periods : int, default 1
Minimum number of observations in window required to have a value
(otherwise result is NA).
center : bool, default False
Set the labels at the center of the window.
axis : int or str, default 0
... | expanding | python | mars-project/mars | mars/dataframe/window/expanding/core.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/window/expanding/core.py | Apache-2.0 |
def rolling(
obj,
window,
min_periods=None,
center=False,
win_type=None,
on=None,
axis=0,
closed=None,
):
"""
Provide rolling window calculations.
Parameters
----------
window : int, or offset
Size of the moving window. This is the number of observations used... |
Provide rolling window calculations.
Parameters
----------
window : int, or offset
Size of the moving window. This is the number of observations used for
calculating the statistic. Each window will be a fixed size.
If its an offset then this will be the time period of each wind... | rolling | python | mars-project/mars | mars/dataframe/window/rolling/core.py | https://github.com/mars-project/mars/blob/master/mars/dataframe/window/rolling/core.py | Apache-2.0 |
def _merge_config(full_config: Dict, config: Dict) -> Dict:
"""
Merge the config to full_config, the config support flatten key, e.g.
config={
'scheduling.autoscale.enabled': True,
'scheduling.autoscale.scheduler_check_interval': 1,
'scheduling.autoscale.scheduler_backlog_timeout': ... |
Merge the config to full_config, the config support flatten key, e.g.
config={
'scheduling.autoscale.enabled': True,
'scheduling.autoscale.scheduler_check_interval': 1,
'scheduling.autoscale.scheduler_backlog_timeout': 1,
'scheduling.autoscale.worker_idle_timeout': 10,
... | _merge_config | python | mars-project/mars | mars/deploy/utils.py | https://github.com/mars-project/mars/blob/master/mars/deploy/utils.py | Apache-2.0 |
async def wait_all_supervisors_ready(endpoint):
"""
Wait till all containers are ready
"""
from ..services.cluster import ClusterAPI
cluster_api = None
while True:
try:
cluster_api = await ClusterAPI.create(endpoint)
break
except: # noqa: E722 # pylint... |
Wait till all containers are ready
| wait_all_supervisors_ready | python | mars-project/mars | mars/deploy/utils.py | https://github.com/mars-project/mars/blob/master/mars/deploy/utils.py | Apache-2.0 |
def new_cluster(
kube_api_client=None,
image=None,
supervisor_num=1,
supervisor_cpu=None,
supervisor_mem=None,
worker_num=1,
worker_cpu=None,
worker_mem=None,
worker_spill_paths=None,
worker_cache_mem=None,
min_worker_num=None,
web_num=1,
web_cpu=None,
web_mem=Non... |
:param kube_api_client: Kubernetes API client, can be created with ``new_client_from_config``
:param image: Docker image to use, ``marsproject/mars:<mars version>`` by default
:param supervisor_num: Number of supervisors in the cluster, 1 by default
:param supervisor_cpu: Number of CPUs for every super... | new_cluster | python | mars-project/mars | mars/deploy/kubernetes/client.py | https://github.com/mars-project/mars/blob/master/mars/deploy/kubernetes/client.py | Apache-2.0 |
async def wait_all_supervisors_ready(self):
"""
Wait till all containers are ready
"""
await wait_all_supervisors_ready(self.args.endpoint) |
Wait till all containers are ready
| wait_all_supervisors_ready | python | mars-project/mars | mars/deploy/kubernetes/core.py | https://github.com/mars-project/mars/blob/master/mars/deploy/kubernetes/core.py | Apache-2.0 |
def new_ray_session(
address: str = None,
session_id: str = None,
backend: str = "mars",
default: bool = True,
**new_cluster_kwargs,
) -> AbstractSession:
"""
Parameters
----------
address: str
mars web server address.
session_id: str
session id. If not specified... |
Parameters
----------
address: str
mars web server address.
session_id: str
session id. If not specified, will be generated automatically.
backend: str
The executor backend. Available values are "mars" and "ray", default is "mars".
default: bool
whether set the ... | new_ray_session | python | mars-project/mars | mars/deploy/oscar/ray.py | https://github.com/mars-project/mars/blob/master/mars/deploy/oscar/ray.py | Apache-2.0 |
async def wait_all_supervisors_ready(self):
"""
Wait till all containers are ready, both in yarn and in Cluster Service
"""
await wait_all_supervisors_ready(self.args.endpoint) |
Wait till all containers are ready, both in yarn and in Cluster Service
| wait_all_supervisors_ready | python | mars-project/mars | mars/deploy/yarn/core.py | https://github.com/mars-project/mars/blob/master/mars/deploy/yarn/core.py | Apache-2.0 |
def score(self, X, y, sample_weight=None, session=None, run_kwargs=None):
"""
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy
which is a harsh metric since you require for each sample that
each label set be c... |
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy
which is a harsh metric since you require for each sample that
each label set be correctly predicted.
Parameters
----------
X : array-like of ... | score | python | mars-project/mars | mars/learn/base.py | https://github.com/mars-project/mars/blob/master/mars/learn/base.py | Apache-2.0 |
def score(self, X, y, sample_weight=None):
"""Return the coefficient of determination :math:`R^2` of the
prediction.
The coefficient :math:`R^2` is defined as :math:`(1 - \\frac{u}{v})`,
where :math:`u` is the residual sum of squares ``((y_true - y_pred)
** 2).sum()`` and :math:... | Return the coefficient of determination :math:`R^2` of the
prediction.
The coefficient :math:`R^2` is defined as :math:`(1 - \frac{u}{v})`,
where :math:`u` is the residual sum of squares ``((y_true - y_pred)
** 2).sum()`` and :math:`v` is the total sum of squares ``((y_true -
y_... | score | python | mars-project/mars | mars/learn/base.py | https://github.com/mars-project/mars/blob/master/mars/learn/base.py | Apache-2.0 |
def _validate_data(
self, X, y=None, reset=True, validate_separately=False, **check_params
):
"""Validate input data and set or check the `n_features_in_` attribute.
Parameters
----------
X : {array-like, sparse matrix, dataframe} of shape \
(n_samples, n_fea... | Validate input data and set or check the `n_features_in_` attribute.
Parameters
----------
X : {array-like, sparse matrix, dataframe} of shape (n_samples, n_features)
The input samples.
y : array-like of shape (n_samples,), default=None
The target... | _validate_data | python | mars-project/mars | mars/learn/base.py | https://github.com/mars-project/mars/blob/master/mars/learn/base.py | Apache-2.0 |
def _check_method(self, method):
"""
Check if self.estimator has 'method'.
Raises
------
AttributeError
"""
estimator = self.estimator
if not hasattr(estimator, method):
msg = "The wrapped estimator '{}' does not have a '{}' method.".format(
... |
Check if self.estimator has 'method'.
Raises
------
AttributeError
| _check_method | python | mars-project/mars | mars/learn/wrappers.py | https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py | Apache-2.0 |
def transform(self, X):
"""
Transform block or partition-wise for Mars inputs.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not h... |
Transform block or partition-wise for Mars inputs.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``transform`` method, then
... | transform | python | mars-project/mars | mars/learn/wrappers.py | https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py | Apache-2.0 |
def score(self, X, y):
"""
Returns the score on the given data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input data, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, s... |
Returns the score on the given data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input data, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples] or [n_samples, ... | score | python | mars-project/mars | mars/learn/wrappers.py | https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py | Apache-2.0 |
def predict(self, X, execute=True):
"""
Predict for X.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
Parameters
----------
X : array-like
... |
Predict for X.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
Parameters
----------
X : array-like
Returns
-------
y : array-like
... | predict | python | mars-project/mars | mars/learn/wrappers.py | https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py | Apache-2.0 |
def predict_proba(self, X, execute=True):
"""
Probability estimates.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``pr... |
Probability estimates.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``AttributeErro... | predict_proba | python | mars-project/mars | mars/learn/wrappers.py | https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py | Apache-2.0 |
def predict_log_proba(self, X, execute=True):
"""
Log of probability estimates.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not ... |
Log of probability estimates.
For Mars inputs, a Mars tensor is returned. For other
inputs (NumPy array, pandas dataframe, scipy sparse matrix), the
regular return value is returned.
If the underlying estimator does not have a ``predict_proba``
method, then an ``Attrib... | predict_log_proba | python | mars-project/mars | mars/learn/wrappers.py | https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py | Apache-2.0 |
def _validate_center_shape(X, n_centers, centers):
"""Check if centers is compatible with X and n_centers"""
if len(centers) != n_centers:
raise ValueError(
"The shape of the initial centers (%s) "
"does not match the number of clusters %i" % (centers.shape, n_centers)
)
... | Check if centers is compatible with X and n_centers | _validate_center_shape | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def _tolerance(X, tol):
"""Return a tolerance which is independent of the dataset"""
variances = mt.var(X, axis=0)
return mt.mean(variances) * tol | Return a tolerance which is independent of the dataset | _tolerance | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def _check_normalize_sample_weight(sample_weight, X):
"""Set sample_weight if None, and check for correct dtype"""
sample_weight_was_none = sample_weight is None
sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
if not sample_weight_was_none:
# normalize the weights to sum ... | Set sample_weight if None, and check for correct dtype | _check_normalize_sample_weight | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def k_means(
X,
n_clusters,
sample_weight=None,
init="k-means||",
n_init=10,
max_iter=300,
verbose=False,
tol=1e-4,
random_state=None,
copy_x=True,
algorithm="auto",
oversampling_factor=2,
init_iter=5,
return_n_iter=False,
):
"""K-means clustering algorithm.
... | K-means clustering algorithm.
Parameters
----------
X : Tensor, shape (n_samples, n_features)
The observations to cluster. It must be noted that the data
will be converted to C ordering, which will cause a memory copy
if the given data is not C-contiguous.
n_clusters : int
... | k_means | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def _labels_inertia(
X, sample_weight, x_squared_norms, centers, session=None, run_kwargs=None
):
"""E step of the K-means EM algorithm.
Compute the labels and the inertia of the given samples and centers.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
... | E step of the K-means EM algorithm.
Compute the labels and the inertia of the given samples and centers.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples to assign to the labels. If sparse matrix, must be in
CSR format.
sampl... | _labels_inertia | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def _init_centroids(
X,
n_clusters=8,
init="k-means++",
random_state=None,
x_squared_norms=None,
init_size=None,
oversampling_factor=2,
init_iter=5,
):
"""Compute the initial centroids
Parameters
----------
X : Tensor of shape (n_samples, n_features)
The input s... | Compute the initial centroids
Parameters
----------
X : Tensor of shape (n_samples, n_features)
The input samples.
n_clusters : int, default=8
number of centroids.
init : {'k-means++', 'k-means||', 'random', tensor, callable}, default="k-means++"
Method for initialization... | _init_centroids | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def fit(self, X, y=None, sample_weight=None, session=None, run_kwargs=None):
"""Compute k-means clustering.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data
will b... | Compute k-means clustering.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training instances to cluster. It must be noted that the data
will be converted to C ordering, which will cause a memory
copy if the given data ... | fit | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def fit_predict(self, X, y=None, sample_weight=None, session=None, run_kwargs=None):
"""Compute cluster centers and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
Parameters
----------
X : {array-like, spa... | Compute cluster centers and predict cluster index for each sample.
Convenience method; equivalent to calling fit(X) followed by
predict(X).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
y : Ign... | fit_predict | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def fit_transform(
self, X, y=None, sample_weight=None, session=None, run_kwargs=None
):
"""Compute clustering and transform X to cluster-distance space.
Equivalent to fit(X).transform(X), but more efficiently implemented.
Parameters
----------
X : {array-like, spar... | Compute clustering and transform X to cluster-distance space.
Equivalent to fit(X).transform(X), but more efficiently implemented.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
y : Ignored
... | fit_transform | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def transform(self, X, session=None, run_kwargs=None):
"""Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the cluster
centers. Note that even if X is sparse, the array returned by
`transform` will typically be dense.
Parameters
... | Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the cluster
centers. Note that even if X is sparse, the array returned by
`transform` will typically be dense.
Parameters
----------
X : {array-like, sparse matrix} of shape (n... | transform | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def _transform(self, X, session=None, run_kwargs=None):
"""guts of transform method; no input validation"""
return euclidean_distances(X, self.cluster_centers_).execute(
session=session, **(run_kwargs or dict())
) | guts of transform method; no input validation | _transform | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def predict(self, X, sample_weight=None, session=None, run_kwargs=None):
"""Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in... | Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
----------
X : {array-like, spar... | predict | python | mars-project/mars | mars/learn/cluster/_kmeans.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py | Apache-2.0 |
def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None):
"""Init n_clusters seeds according to k-means++
Parameters
----------
X : array or sparse matrix, shape (n_samples, n_features)
The data to pick seeds for. To avoid memory copy, the input data
should be doub... | Init n_clusters seeds according to k-means++
Parameters
----------
X : array or sparse matrix, shape (n_samples, n_features)
The data to pick seeds for. To avoid memory copy, the input data
should be double precision (dtype=np.float64).
n_clusters : integer
The number of seeds ... | _k_init | python | mars-project/mars | mars/learn/cluster/_k_means_init.py | https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_k_means_init.py | Apache-2.0 |
def pick_workers(workers, size):
"""
Pick workers from a list.
This method will try to pick workers as balanced as it can.
1. If size <= len(workers), randomly pick workers from the list.
2. If size > len(workers), just select all workers in a random order,
then see the rest size, if it's s... |
Pick workers from a list.
This method will try to pick workers as balanced as it can.
1. If size <= len(workers), randomly pick workers from the list.
2. If size > len(workers), just select all workers in a random order,
then see the rest size, if it's still more than the workers size,
... | pick_workers | python | mars-project/mars | mars/learn/contrib/utils.py | https://github.com/mars-project/mars/blob/master/mars/learn/contrib/utils.py | Apache-2.0 |
def run_pytorch_script(
script: Union[bytes, str, BinaryIO, TextIO],
n_workers: int,
data: Dict[str, TileableType] = None,
gpu: Optional[bool] = None,
command_argv: List[str] = None,
retry_when_fail: bool = False,
session: SessionType = None,
run_kwargs: Dict[str, Any] = None,
port: ... |
Run PyTorch script in Mars cluster.
Parameters
----------
script: str or file-like object
Script to run
n_workers : int
Number of PyTorch workers
data : dict
Variable name to data.
gpu : bool
Run PyTorch script on GPU
command_argv : list
Extra co... | run_pytorch_script | python | mars-project/mars | mars/learn/contrib/pytorch/run_script.py | https://github.com/mars-project/mars/blob/master/mars/learn/contrib/pytorch/run_script.py | Apache-2.0 |
def to_tf(self) -> "tf.data.Dataset":
"""Get TF Dataset.
convert into a tensorflow.data.Dataset
"""
def make_generator(): # pragma: no cover
if not self._executed:
self._execute()
self._executed = True
for i in range(len(self._t... | Get TF Dataset.
convert into a tensorflow.data.Dataset
| to_tf | python | mars-project/mars | mars/learn/contrib/tensorflow/dataset.py | https://github.com/mars-project/mars/blob/master/mars/learn/contrib/tensorflow/dataset.py | Apache-2.0 |
def gen_tensorflow_dataset(
tensors,
output_shapes: Tuple[int, ...] = None,
output_types: Tuple[np.dtype, ...] = None,
fetch_kwargs=None,
):
"""
convert mars data type to tf.data.Dataset. Note this is based tensorflow 2.0
For example
-----------
>>> # convert a tensor to tf.data.Data... |
convert mars data type to tf.data.Dataset. Note this is based tensorflow 2.0
For example
-----------
>>> # convert a tensor to tf.data.Dataset.
>>> data = mt.tensor([[1, 2], [3, 4]])
>>> dataset = gen_tensorflow_dataset(data)
>>> list(dataset.as_numpy_iterator())
[array([1, 2]), array([... | gen_tensorflow_dataset | python | mars-project/mars | mars/learn/contrib/tensorflow/dataset.py | https://github.com/mars-project/mars/blob/master/mars/learn/contrib/tensorflow/dataset.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.