code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return super(ODPSModelExpr, self).persist(name, project=project, drop_model=drop_model, **kwargs) | def persist(self, name, project=None, drop_model=False, **kwargs) | Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation | 5.436018 | 7.599185 | 0.715342 |
return super(PmmlModel, self).predict(*args, **kwargs) | def predict(self, *args, **kwargs) | Predict given DataFrame using the given model. Actual prediction steps will not
be executed till an operational step is called.
After execution, three columns will be appended to the table:
+-------------------+--------+----------------------------------------------------+
| Field name... | 6.744922 | 7.430192 | 0.907772 |
return super(TablesModel, self).predict(*args, **kwargs) | def predict(self, *args, **kwargs) | Predict given DataFrame using the given model. Actual prediction steps will not
be executed till an operational step is called.
:param list[DataFrame] args: input DataFrames to be predicted
:param kwargs: named input DataFrames or prediction parameters, details can be found in ''Predictor Param... | 8.540328 | 16.125841 | 0.529605 |
return self.parent.get_worker_log(self.log_id, log_type, size=size) | def get_log(self, log_type, size=0) | Get logs from worker.
:param log_type: type of logs. Possible log types contains {log_types}
:param size: length of the log to retrieve
:return: log content | 6.372047 | 7.547813 | 0.844224 |
fields = self._get_fields_list_from_eps(sources)
target._ml_fields = copy.deepcopy(fields[0]) | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 16.583626 | 13.235984 | 1.25292 |
fields = self._get_fields_list_from_eps(sources)
feature_set = set(self.feature_names)
target._ml_fields = list(self._add_field_roles(fields[0], feature_set, self.role, self.augment)) | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 12.289283 | 11.09137 | 1.108004 |
fields = self._get_fields_list_from_eps(sources)
feature_set = set(self.exclude_names)
target._ml_fields = list(self._clear_field_roles(fields[0], feature_set)) | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 15.221953 | 13.329932 | 1.141938 |
fields = self._get_fields_list_from_eps(sources)
ret_fields = fields[0]
if self.clear_feature:
ret_fields = list(self._remove_field_roles(ret_fields, set(six.iterkeys(self.field_mapping)),
FieldRole.FEATURE))
tar... | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 9.202547 | 8.570505 | 1.073746 |
fields = self._get_fields_list_from_eps(sources)
for f in fields[0]:
if f.name in self.continuity:
f.continuity = self.continuity[f.name]
for field_name in set(six.iterkeys(self.continuity)) - set(f.name for f in fields[0]):
fields[0].append(MLFie... | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 4.630218 | 4.542748 | 1.019255 |
existing_ml_fields = self._get_fields_list_from_eps(sources)
dup_ml_fields = [f.copy() for f in self.fields]
if self.is_append:
src = list([copy.deepcopy(f) for f in existing_ml_fields[0]])
src.extend(dup_ml_fields)
target._ml_fields = src
els... | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 5.866848 | 5.587869 | 1.049926 |
existing_ml_fields = self._get_fields_list_from_eps(sources)
def gen_field(field_str):
parts = field_str.split(':')
if len(parts) > 2:
roles = set(MLField.translate_role_name(rn) for rn in parts[2].strip().split('#')) - set([None])
else:
... | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 5.08679 | 4.892172 | 1.039782 |
existing_fields = self._get_fields_list_from_eps(sources)
def trans_columns(tid, fields):
sel_cols = self._selected_cols.get(tid)
exc_cols = self._excluded_cols.get(tid)
for field in fields:
if field.role is None:
continue... | def execute(self, sources, target) | :type sources: list[DFAdapter]
:type target: DFAdapter | 3.700257 | 3.637248 | 1.017323 |
if isinstance(expr, SequenceExpr):
unique_input = _extract_unique_input(expr)
if unique_input:
return nunique(unique_input).rename('count')
else:
return Count(_value_type=types.int64, _input=expr)
elif isinstance(expr, SequenceGroupBy):
return Groupe... | def count(expr) | Value counts
:param expr:
:return: | 3.339947 | 3.319963 | 1.006019 |
ddof = kw.get('ddof', kw.get('_ddof', 1))
output_type = _stats_type(expr)
return _reduction(expr, Var, output_type, _ddof=ddof) | def var(expr, **kw) | Variance
:param expr:
:param ddof: degree of freedom
:param kw:
:return: | 7.495971 | 7.196653 | 1.041591 |
output_type = None
if isinstance(expr, (SequenceExpr, SequenceGroupBy)):
if expr._data_type == types.boolean:
output_type = types.int64
else:
output_type = expr._data_type
return _reduction(expr, Sum, output_type) | def sum_(expr) | Sum value
:param expr:
:return: | 5.215709 | 5.406939 | 0.964633 |
ddof = kw.get('ddof', kw.get('_ddof', 1))
output_type = _stats_type(expr)
return _reduction(expr, Std, output_type, _ddof=ddof) | def std(expr, **kw) | Standard deviation.
:param expr:
:param kw:
:return: | 7.562068 | 7.323832 | 1.032529 |
prob = kw.get('_prob', prob)
output_type = _stats_type(expr)
if isinstance(prob, (list, set)) and not isinstance(expr, GroupBy):
output_type = types.List(output_type)
return _reduction(expr, Quantile, output_type, _prob=prob) | def quantile(expr, prob=None, **kw) | Percentile value.
:param expr:
:param prob: probability or list of probabilities, in [0, 1]
:return: | 6.227741 | 6.476192 | 0.961636 |
output_type = types.int64
if isinstance(expr, SequenceExpr):
return NUnique(_value_type=output_type, _inputs=[expr])
elif isinstance(expr, SequenceGroupBy):
return GroupedNUnique(_data_type=output_type, _inputs=[expr.to_column()], _grouped=expr.input)
elif isinstance(expr, Collecti... | def nunique(expr) | The distinct count.
:param expr:
:return: | 3.635456 | 3.891512 | 0.934201 |
if others is not None:
from .strings import _cat as cat_str
return cat_str(expr, others, sep=sep, na_rep=na_rep)
return _cat(expr, sep=sep, na_rep=na_rep) | def cat(expr, others=None, sep=None, na_rep=None) | Concatenate strings in sequence with given separator
:param expr:
:param others: other sequences
:param sep: string or None, default None
:param na_rep: string or None default None, if None, NA in the sequence are ignored
:return: | 2.802534 | 3.471532 | 0.80729 |
if not isinstance(order, six.integer_types):
raise ValueError('Only integer-ordered moments are supported.')
if order < 0:
raise ValueError('Only non-negative orders are supported.')
output_type = _stats_type(expr)
return _reduction(expr, Moment, output_type, _order=order, _center=c... | def moment(expr, order, central=False) | Calculate the n-th order moment of the sequence
:param expr:
:param order: moment order, must be an integer
:param central: if central moments are to be computed.
:return: | 4.447276 | 5.336095 | 0.833433 |
unique = kwargs.get('unique', kwargs.get('_unique', False))
output_type = None
if isinstance(expr, (SequenceExpr, SequenceGroupBy)):
output_type = types.List(expr._data_type)
return _reduction(expr, ToList, output_type, _unique=unique) | def tolist(expr, **kwargs) | Pack all data in the sequence into a list
:param expr:
:param unique: make every elements in the sequence to be unique
:return: | 7.17535 | 7.512676 | 0.955099 |
instance_status = Instance.InstanceStatus(status='Terminated')
xml_content = instance_status.serialize()
headers = {'Content-Type': 'application/xml'}
self._client.put(self.resource(), xml_content, headers=headers) | def stop(self) | Stop this instance.
:return: None | 6.812514 | 6.014363 | 1.132707 |
results = self.get_task_results_without_format()
if options.tunnel.string_as_binary:
return compat.OrderedDict([(k, bytes(result)) for k, result in six.iteritems(results)])
else:
return compat.OrderedDict([(k, str(result)) for k, result in six.iteritems(results)... | def get_task_results(self) | Get all the task results.
:return: a dict which key is task name, and value is the task result as string
:rtype: dict | 5.065831 | 4.913794 | 1.030941 |
params = {'instancesummary': '', 'taskname': task_name}
resp = self._client.get(self.resource(), params=params)
map_reduce = resp.json().get('Instance')
if map_reduce:
json_summary = map_reduce.get('JsonSummary')
if json_summary:
summary... | def get_task_summary(self, task_name) | Get a task's summary, mostly used for MapReduce.
:param task_name: task name
:return: summary as a dict parsed from JSON
:rtype: dict | 4.860753 | 5.009726 | 0.970263 |
params = {'taskstatus': ''}
resp = self._client.get(self.resource(), params=params)
self.parse(self._client, resp, obj=self)
return dict([(task.name, task) for task in self._tasks]) | def get_task_statuses(self) | Get all tasks' statuses
:return: a dict which key is the task name and value is the :class:`odps.models.Instance.Task` object
:rtype: dict | 6.524499 | 6.239735 | 1.045637 |
summary = self.get_task_summary(task_name)
if summary is None:
return None
if 'Cost' in summary:
task_cost = summary['Cost']
cpu_cost = task_cost.get('CPU')
memory = task_cost.get('Memory')
input_size = task_cost.get('Input')... | def get_task_cost(self, task_name) | Get task cost
:param task_name: name of the task
:return: task cost
:rtype: Instance.TaskCost
:Example:
>>> cost = instance.get_task_cost(instance.get_task_names()[0])
>>> cost.cpu_cost
200
>>> cost.memory_cost
4096
>>> cost.input_size
... | 3.241779 | 2.595384 | 1.249055 |
params = OrderedDict([('info', ''), ('taskname', task_name), ('key', key)])
resp = self._client.get(self.resource(), params=params)
return resp.text | def get_task_info(self, task_name, key) | Get task related information.
:param task_name: name of the task
:param key: key of the information item
:return: a string of the task information | 6.186136 | 9.974044 | 0.620223 |
params = OrderedDict([('info', ''), ('taskname', task_name)])
headers = {'Content-Type': 'application/xml'}
body = self.TaskInfo(key=key, value=value).serialize()
self._client.put(self.resource(), params=params, headers=headers, data=body) | def put_task_info(self, task_name, key, value) | Put information into a task.
:param task_name: name of the task
:param key: key of the information item
:param value: value of the information item | 4.872259 | 6.556242 | 0.743148 |
params = OrderedDict([('instancequota', ''), ('taskname', task_name)])
resp = self._client.get(self.resource(), params=params)
return json.loads(resp.text) | def get_task_quota(self, task_name) | Get queueing info of the task.
Note that time between two calls should larger than 30 seconds, otherwise empty dict is returned.
:param task_name: name of the task
:return: quota info in dict format | 6.348227 | 9.645506 | 0.658154 |
resp = self.get_task_result(self.get_task_names()[0])
cost = json.loads(resp)
sql_cost = cost['Cost']['SQL']
udf_num = sql_cost.get('UDF')
complexity = sql_cost.get('Complexity')
input_size = sql_cost.get('Input')
return Instance.SQLCost(udf_num, complex... | def get_sql_task_cost(self) | Get cost information of the sql task.
Including input data size, number of UDF, Complexity of the sql task
:return: cost info in dict format | 4.987595 | 4.085668 | 1.220754 |
retry_num = options.retry_times
while retry_num > 0:
try:
return self.status == Instance.Status.TERMINATED
except (errors.InternalServerError, errors.RequestTimeTooSkewed):
retry_num -= 1
if not retry or retry_num <= 0:
... | def is_terminated(self, retry=False) | If this instance has finished or not.
:return: True if finished else False
:rtype: bool | 4.24485 | 4.51896 | 0.939342 |
if not self.is_terminated(retry=retry):
return False
retry_num = options.retry_times
while retry_num > 0:
try:
statuses = self.get_task_statuses()
return all(task.status == Instance.Task.TaskStatus.SUCCESS
... | def is_successful(self, retry=False) | If the instance runs successfully.
:return: True if successful else False
:rtype: bool | 4.427839 | 4.349315 | 1.018054 |
while not self.is_terminated(retry=True):
try:
time.sleep(interval)
except KeyboardInterrupt:
break | def wait_for_completion(self, interval=1) | Wait for the instance to complete, and neglect the consequence.
:param interval: time interval to check
:return: None | 5.359801 | 5.171715 | 1.036368 |
self.wait_for_completion(interval=interval)
if not self.is_successful(retry=True):
for task_name, task in six.iteritems(self.get_task_statuses()):
exc = None
if task.status == Instance.Task.TaskStatus.FAILED:
exc = errors.parse_i... | def wait_for_success(self, interval=1) | Wait for instance to complete, and check if the instance is successful.
:param interval: time interval to check
:return: None
:raise: :class:`odps.errors.ODPSError` if the instance failed | 3.853121 | 3.342858 | 1.152643 |
params = {'instanceprogress': task_name, 'taskname': task_name}
resp = self._client.get(self.resource(), params=params)
return Instance.Task.TaskProgress.parse(self._client, resp) | def get_task_progress(self, task_name) | Get task's current progress
:param task_name: task_name
:return: the task's progress
:rtype: :class:`odps.models.Instance.Task.TaskProgress` | 9.291867 | 6.128972 | 1.516056 |
def _get_detail():
from ..compat import json # fix object_pairs_hook parameter for Py2.6
params = {'instancedetail': '',
'taskname': task_name}
resp = self._client.get(self.resource(), params=params)
return json.loads(resp.text if... | def get_task_detail(self, task_name) | Get task's detail
:param task_name: task name
:return: the task's detail
:rtype: list or dict according to the JSON | 5.567306 | 5.996946 | 0.928357 |
from ..compat import json # fix object_pairs_hook parameter for Py2.6
params = {'detail': '',
'taskname': task_name}
resp = self._client.get(self.resource(), params=params)
res = resp.text if six.PY3 else resp.content
try:
return json.lo... | def get_task_detail2(self, task_name) | Get task's detail v2
:param task_name: task name
:return: the task's detail
:rtype: list or dict according to the JSON | 5.460871 | 5.477434 | 0.996976 |
if task_name is None and json_obj is None:
raise ValueError('Either task_name or json_obj should be provided')
if json_obj is None:
json_obj = self.get_task_detail2(task_name)
return WorkerDetail2.extract_from_json(json_obj, client=self._client, parent=self) | def get_task_workers(self, task_name=None, json_obj=None) | Get workers from task
:param task_name: task name
:param json_obj: json object parsed from get_task_detail2
:return: list of workers
.. seealso:: :class:`odps.models.Worker` | 3.37816 | 3.136201 | 1.07715 |
params = OrderedDict([('log', ''), ('id', log_id)])
if log_type is not None:
log_type = log_type.lower()
if log_type not in LOG_TYPES_MAPPING:
raise ValueError('log_type should choose a value in ' +
' '.join(six.iterkeys(L... | def get_worker_log(self, log_id, log_type, size=0) | Get logs from worker.
:param log_id: id of log, can be retrieved from details.
:param log_type: type of logs. Possible log types contains {log_types}
:param size: length of the log to retrieve
:return: log content | 3.069606 | 3.578802 | 0.857719 |
hours = hours or options.log_view_hours
project = self.project
url = '%s/authorization' % project.resource()
policy = {
'expires_in_hours': hours,
'policy': {
'Statement': [{
'Action': ['odps:Read'],
... | def get_logview_address(self, hours=None) | Get logview address of the instance object by hours.
:param hours:
:return: logview address
:rtype: str | 4.011481 | 4.103159 | 0.977657 |
use_tunnel = kwargs.get('use_tunnel', kwargs.get('tunnel'))
auto_fallback_result = use_tunnel is None
if use_tunnel is None:
use_tunnel = options.tunnel.use_instance_tunnel
result_fallback_errors = (errors.InvalidProjectTable, errors.InvalidArgument)
if use_t... | def open_reader(self, *args, **kwargs) | Open the reader to read records from the result of the instance. If `tunnel` is `True`,
instance tunnel will be used. Otherwise conventional routine will be used. If instance tunnel
is not available and `tunnel` is not specified,, the method will fall back to the
conventional routine.
No... | 4.665399 | 4.059751 | 1.149184 |
try:
ip = get_ipython()
front_end = (
ip.config.get('KernelApp', {}).get('parent_appname', "") or
ip.config.get('IPKernelApp', {}).get('parent_appname', "")
)
if 'qtconsole' in front_end.lower():
return True
except:
return False
... | def in_qtconsole() | check if we're inside an IPython qtconsole
DEPRECATED: This is no longer needed, or working, in IPython 3 and above. | 2.67926 | 2.562464 | 1.04558 |
display_width = options.display.width
# deprecated.
display_height = options.display.max_rows
# Consider
# interactive shell terminal, can detect term size
# interactive non-shell terminal (ipnb/ipqtconsole), cannot detect term
# size non-interactive script, should disregard term size
... | def get_console_size() | Return console size as tuple = (width, height).
Returns (None,None) in non-interactive session. | 9.301421 | 8.885211 | 1.046843 |
if stderr:
stream = 'stderr'
else:
stream = 'stdout'
sys_stream = getattr(sys, stream)
if IPythonIOStream is None:
return sys_stream
ipyio_stream = getattr(ipyio, stream)
if isatty(sys_stream) and isatty(ipyio_stream):
# Use the IPython console output st... | def _get_stdout(stderr=False) | This utility function contains the logic to determine what streams to use
by default for standard out/err.
Typically this will just return `sys.stdout`, but it contains additional
logic for use in IPython on Windows to determine the correct stream to use
(usually ``IPython.util.io.stdout`` but only if ... | 4.727082 | 4.271493 | 1.106658 |
if (multiprocessing.current_process().name != 'MainProcess' or
threading.current_thread().getName() != 'MainThread'):
return False
if hasattr(file, 'isatty'):
return file.isatty()
elif (OutStream is not None and
isinstance(file, (OutStream, IPythonIOStream)) and
... | def isatty(file) | Returns `True` if `file` is a tty.
Most built-in Python file-like objects have an `isatty` member,
but some user-defined types may not, so this assumes those are not
ttys. | 5.028575 | 5.138751 | 0.97856 |
if file is None:
file = _get_stdout()
try:
s = struct.pack(str("HHHH"), 0, 0, 0, 0)
x = fcntl.ioctl(file, termios.TIOCGWINSZ, s)
(lines, width, xpixels, ypixels) = struct.unpack(str("HHHH"), x)
if lines > 12:
lines -= 6
if width > 10:
... | def _terminal_size(file=None) | Returns a tuple (height, width) containing the height and width of
the terminal.
This function will look for the width in height in multiple areas
before falling back on the width and height in astropy's
configuration. | 3.102229 | 2.991151 | 1.037135 |
color_mapping = {
'black': '0;30',
'red': '0;31',
'green': '0;32',
'brown': '0;33',
'blue': '0;34',
'magenta': '0;35',
'cyan': '0;36',
'lightgrey': '0;37',
'default': '0;39',
'darkgrey': '1;30',
'lightred': '1;31',
... | def _color_text(text, color) | Returns a string wrapped in ANSI color codes for coloring the
text in a terminal::
colored_text = color_text('Here is a message', 'blue')
This won't actually effect the text until it is printed to the
terminal.
Parameters
----------
text : str
The string to return, bounded by ... | 1.70878 | 1.65841 | 1.030373 |
enc = locale.getpreferredencoding()
try:
try:
return s.decode(enc)
except LookupError:
enc = _DEFAULT_ENCODING
return s.decode(enc)
except UnicodeDecodeError:
return s.decode('latin-1') | def _decode_preferred_encoding(s) | Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8. | 3.172688 | 2.793579 | 1.135707 |
if IPythonIOStream is not None and isinstance(fileobj, IPythonIOStream):
# If the output stream is an IPython.utils.io.IOStream object that's
# not going to be very helpful to us since it doesn't raise any
# exceptions when an error occurs writing to its underlying stream.
# Th... | def _write_with_fallback(s, write, fileobj) | Write the supplied string with the given write function like
``write(s)``, but use a writer for the locale's preferred encoding in case
of a UnicodeEncodeError. Failing that attempt to write with 'utf-8' or
'latin-1'. | 4.597034 | 4.641618 | 0.990395 |
file = kwargs.get('file', _get_stdout())
end = kwargs.get('end', '\n')
write = file.write
if isatty(file) and options.console.use_color:
for i in range(0, len(args), 2):
msg = args[i]
if i + 1 == len(args):
color = ''
else:
... | def color_print(*args, **kwargs) | Prints colors and styles to the terminal uses ANSI escape
sequences.
::
color_print('This is the color ', 'default', 'GREEN', 'green')
Parameters
----------
positional args : str
The positional arguments come in pairs (*msg*, *color*), where
*msg* is the string to display a... | 3.968804 | 3.843101 | 1.032709 |
units = [
('y', 60 * 60 * 24 * 7 * 52),
('w', 60 * 60 * 24 * 7),
('d', 60 * 60 * 24),
('h', 60 * 60),
('m', 60),
('s', 1),
]
seconds = int(seconds)
if seconds < 60:
return ' {0:2d}s'.format(seconds)
for i in range(len(units) - 1):
... | def human_time(seconds) | Returns a human-friendly time string that is always exactly 6
characters long.
Depending on the number of seconds given, can be one of::
1w 3d
2d 4h
1h 5m
1m 4s
15s
Will be in color if console coloring is turned on.
Parameters
----------
seconds : in... | 1.917488 | 1.933066 | 0.991941 |
suffixes = ' kMGTPEZY'
if size == 0:
num_scale = 0
else:
num_scale = int(math.floor(math.log(size) / math.log(1000)))
num_scale = max(num_scale, 0)
if num_scale >= len(suffixes):
suffix = '?'
else:
suffix = suffixes[num_scale]
num_scale = int(math.pow(100... | def human_file_size(size) | Returns a human-friendly string representing a file size
that is 2-4 characters long.
For example, depending on the number of bytes given, can be one
of::
256b
64k
1.1G
Parameters
----------
size : int
The size of the file (in bytes)
Returns
-------
... | 2.208159 | 2.260366 | 0.976903 |
# Update self.value
if value is None:
value = self._current_value + 1
self._current_value = value
# Choose the appropriate environment
if self._ipython_widget:
try:
self._update_ipython_widget(value)
except RuntimeErr... | def update(self, value=None) | Update progress bar via the console or notebook accordingly. | 4.65118 | 3.804784 | 1.222456 |
if self._total == 0:
frac = 1.0
else:
frac = float(value) / float(self._total)
file = self._file
write = file.write
if frac > 1:
bar_fill = int(self._bar_length)
else:
bar_fill = int(float(self._bar_length) * fra... | def _update_console(self, value=None) | Update the progress bar to the given value (out of the total
given to the constructor). | 2.972015 | 2.841837 | 1.045808 |
# Create and display an empty progress bar widget,
# if none exists.
if not hasattr(self, '_widget'):
self._widget = create_progress_widget()
if in_ipython_frontend() and is_widgets_available():
display(self._widget)
self._widget.valu... | def _update_ipython_widget(self, value=None) | Update the progress bar to the given value (out of a total
given to the constructor).
This method is for use in the IPython notebook 2+. | 4.574762 | 4.54192 | 1.007231 |
results = []
if file is None:
file = _get_stdout()
with cls(len(items), file=file) as bar:
step_size = max(200, bar._bar_length)
steps = max(int(float(len(items)) / step_size), 1)
if not multiprocess:
for i, item in enum... | def map(cls, function, items, multiprocess=False, file=None) | Does a `map` operation while displaying a progress bar with
percentage complete.
::
def work(i):
print(i)
ProgressBar.map(work, range(50))
Parameters
----------
function : function
Function to call for each step
ite... | 2.531228 | 2.704137 | 0.936058 |
# to make the class pickled right by the cloudpickle
with open(os.path.join(path, 'lib', 'hll.py')) as hll_file:
local = {}
six.exec_(hll_file.read(), local)
HyperLogLog = local['HyperLogLog']
return expr.agg(HyperLogLog, rtype=types.int64, args=(error_rate, splitter)) | def hll_count(expr, error_rate=0.01, splitter=None) | Calculate HyperLogLog count
:param expr:
:param error_rate: error rate
:type error_rate: float
:param splitter: the splitter to split the column value
:return: sequence or scalar
:Example:
>>> df = DataFrame(pd.DataFrame({'a': np.random.randint(100000, size=100000)}))
>>> df.a.hll_cou... | 6.697018 | 8.064254 | 0.830457 |
if not isinstance(column, Column):
raise TypeError('bloomfilter can only filter on the column of a collection')
# to make the class pickled right by the cloudpickle
with open(os.path.join(path, 'lib', 'bloomfilter.py')) as bloomfilter_file:
local = {}
six.exec_(bloomfilter_fi... | def bloomfilter(collection, on, column, capacity=3000, error_rate=0.01) | Filter collection on the `on` sequence by BloomFilter built by `column`
:param collection:
:param on: sequence or column name
:param column: instance of Column
:param capacity: numbers of capacity
:type capacity: int
:param error_rate: error rate
:type error_rate: float
:return: collect... | 4.256764 | 4.426064 | 0.961749 |
if expr._data_type == types.boolean:
output_type = types.int64
else:
output_type = expr._data_type
return _cumulative_op(expr, CumSum, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following, data_type=o... | def cumsum(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None) | Calculate cumulative summation of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
:param f... | 2.912203 | 3.694715 | 0.788208 |
return _cumulative_op(expr, CumMax, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following) | def cummax(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None) | Calculate cumulative maximum of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
:param fol... | 2.752125 | 4.888172 | 0.563017 |
return _cumulative_op(expr, CumMin, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following) | def cummin(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None) | Calculate cumulative minimum of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
:param fol... | 2.674537 | 4.758255 | 0.562083 |
data_type = _stats_type(expr)
return _cumulative_op(expr, CumMean, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following, data_type=data_type) | def cummean(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None) | Calculate cumulative mean of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
:param follow... | 3.352082 | 4.753006 | 0.705255 |
data_type = _stats_type(expr)
return _cumulative_op(expr, CumMedian, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following, data_type=data_type) | def cummedian(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None) | Calculate cumulative median of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
:param foll... | 3.484042 | 4.816681 | 0.723328 |
data_type = types.int64
return _cumulative_op(expr, CumCount, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following, data_type=data_type) | def cumcount(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None) | Calculate cumulative count of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
:param follo... | 3.266847 | 5.407043 | 0.604184 |
data_type = _stats_type(expr)
return _cumulative_op(expr, CumStd, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following, data_type=data_type) | def cumstd(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None) | Calculate cumulative standard deviation of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
... | 3.33079 | 4.740475 | 0.702628 |
return _cumulative_op(expr, NthValue, data_type=expr._data_type, sort=sort,
ascending=ascending, _nth=nth, _skip_nulls=skip_nulls) | def nth_value(expr, nth, skip_nulls=False, sort=None, ascending=True) | Get nth value of a grouped and sorted expression.
:param expr: expression for calculation
:param nth: integer position
:param skip_nulls: whether to skip null values, False by default
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated c... | 4.68038 | 6.872513 | 0.681029 |
return _rank_op(expr, Rank, types.int64, sort=sort, ascending=ascending) | def rank(expr, sort=None, ascending=True) | Calculate rank of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column | 7.176695 | 16.513319 | 0.4346 |
return _rank_op(expr, DenseRank, types.int64, sort=sort, ascending=ascending) | def dense_rank(expr, sort=None, ascending=True) | Calculate dense rank of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column | 6.013503 | 13.539755 | 0.444137 |
return _rank_op(expr, PercentRank, types.float64, sort=sort, ascending=ascending) | def percent_rank(expr, sort=None, ascending=True) | Calculate percentage rank of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column | 6.664088 | 14.405268 | 0.462615 |
return _rank_op(expr, RowNumber, types.int64, sort=sort, ascending=ascending) | def row_number(expr, sort=None, ascending=True) | Calculate row number of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column | 8.052814 | 17.907358 | 0.449693 |
if labels is None or labels:
raise NotImplementedError('Showing bins or customizing labels not supported')
return _rank_op(expr, QCut, types.int64, sort=sort, ascending=ascending,
_bins=bins) | def qcut(expr, bins, labels=False, sort=None, ascending=True) | Get quantile-based bin indices of every element of a grouped and sorted expression.
The indices of bins start from 0. If cuts are not of equal sizes, extra items will
be appended into the first group.
:param expr: expression for calculation
:param bins: number of bins
:param sort: name of the sort ... | 13.145217 | 20.814676 | 0.631536 |
return _rank_op(expr, CumeDist, types.float64, sort=sort, ascending=ascending) | def cume_dist(expr, sort=None, ascending=True) | Calculate cumulative ratio of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column | 7.44106 | 15.138895 | 0.491519 |
return _shift_op(expr, Lag, offset, default=default,
sort=sort, ascending=ascending) | def lag(expr, offset, default=None, sort=None, ascending=True) | Get value in the row ``offset`` rows prior to the current row.
:param offset: the offset value
:param default: default value for the function, when there are no rows satisfying the offset
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort ... | 4.95166 | 11.484561 | 0.431158 |
return _shift_op(expr, Lead, offset, default=default,
sort=sort, ascending=ascending) | def lead(expr, offset, default=None, sort=None, ascending=True) | Get value in the row ``offset`` rows after to the current row.
:param offset: the offset value
:param default: default value for the function, when there are no rows satisfying the offset
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort ... | 5.88261 | 14.172899 | 0.41506 |
url = self.resource()
params = {'data': ''}
resp = self._client.get(url, params=params)
return resp.text | def get_model(self) | Get PMML text of the current model. Note that model file obtained
via this method might be incomplete due to size limitations. | 8.61594 | 6.97299 | 1.235616 |
host_id, msg, code = None, None, None
try:
content = resp.content
root = ET.fromstring(content)
code = root.find('./Code').text
msg = root.find('./Message').text
request_id = root.find('./RequestId').text
host_id = root.find('./HostId').text
except ETPars... | def parse_response(resp) | Parses the content of response and returns an exception object. | 2.55328 | 2.487595 | 1.026405 |
e = None
try:
e = parse_response(resp)
except:
# Error occurred during parsing the response. We ignore it and delegate
# the situation to caller to handle.
LOG.debug(utils.stringify_expt())
if e is not None:
raise e
if resp.status_code == 404:
r... | def throw_if_parsable(resp) | Try to parse the content of the response and raise an exception
if neccessary. | 5.250085 | 5.147782 | 1.019873 |
from .specialized import build_merge_expr
from ..utils import ML_ARG_PREFIX
if len(data_frames) <= 1:
raise ValueError('Count of DataFrames should be at least 2.')
norm_data_pairs = []
df_tuple = collections.namedtuple('MergeTuple', 'df cols exclude')
for pair in data_frames:
... | def merge_data(*data_frames, **kwargs) | Merge DataFrames by column. Number of rows in tables must be the same.
This method can be called both outside and as a DataFrame method.
:param list[DataFrame] data_frames: DataFrames to be merged.
:param bool auto_rename: if True, fields in source DataFrames will be renamed in the output.
:return: m... | 3.623585 | 3.584248 | 1.010975 |
if not args:
raise ValueError("Field list cannot be None.")
new_df = copy_df(self)
fields = _render_field_set(args)
self._assert_ml_fields_valid(*fields)
new_df._perform_operation(op.ExcludeFieldsOperation(fields))
return new_df | def exclude_fields(self, *args) | Exclude one or more fields from feature fields.
:rtype: DataFrame | 8.405705 | 8.287058 | 1.014317 |
if not args:
raise ValueError("Field list cannot be empty.")
# generate selected set from args
augment = kwargs.get('add', False)
fields = _render_field_set(args)
self._assert_ml_fields_valid(*fields)
return _batch_change_roles(self, fields, FieldRole... | def select_features(self, *args, **kwargs) | Select one or more fields as feature fields.
:rtype: DataFrame | 14.110968 | 14.121519 | 0.999253 |
if f is None:
raise ValueError("Field name cannot be None.")
self._assert_ml_fields_valid(f)
return _change_singleton_roles(self, {f: FieldRole.WEIGHT}, clear_feature=True) | def weight_field(self, f) | Select one field as the weight field.
Note that this field will be exclude from feature fields.
:param f: Selected weight field
:type f: str
:rtype: DataFrame | 13.222857 | 14.151463 | 0.934381 |
if f is None:
raise ValueError("Label field name cannot be None.")
self._assert_ml_fields_valid(f)
return _change_singleton_roles(self, {_get_field_name(f): FieldRole.LABEL}, clear_feature=True) | def label_field(self, f) | Select one field as the label field.
Note that this field will be exclude from feature fields.
:param f: Selected label field
:type f: str
:rtype: DataFrame | 11.743829 | 12.338317 | 0.951818 |
new_df = copy_df(self)
fields = _render_field_set(args)
self._assert_ml_fields_valid(*fields)
new_df._perform_operation(op.FieldContinuityOperation(dict((_get_field_name(f), True) for f in fields)))
return new_df | def continuous(self, *args) | Set fields to be continuous.
:rtype: DataFrame
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=DISCRETE, f2=DISCRETE
>>> # Now we want to set ``f1`` and ``f2`` into continuous
>>> new_ds = df.continuous('f1 f2') | 10.624997 | 10.936687 | 0.9715 |
new_df = copy_df(self)
fields = _render_field_set(args)
self._assert_ml_fields_valid(*fields)
new_df._perform_operation(op.FieldContinuityOperation(dict((_get_field_name(f), False) for f in fields)))
return new_df | def discrete(self, *args) | Set fields to be discrete.
:rtype: DataFrame
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuous
>>> new_ds = df.discrete('f1 f2') | 10.822805 | 11.75777 | 0.920481 |
new_df = copy_df(self)
fields = _render_field_set(args)
self._assert_ml_fields_valid(*fields)
new_df._perform_operation(
op.FieldKVConfigOperation(dict((_get_field_name(f), KVConfig(**kwargs)) for f in fields)))
return new_df | def key_value(self, *args, **kwargs) | Set fields to be key-value represented.
:rtype: DataFrame
:Example:
>>> new_ds = df.key_value('f1 f2', kv=':', item=',') | 12.434845 | 14.809889 | 0.839631 |
new_df = copy_df(self)
fields = _render_field_set(args)
self._assert_ml_fields_valid(*fields)
new_df._perform_operation(op.FieldKVConfigOperation(dict((_get_field_name(f), None) for f in fields)))
return new_df | def erase_key_value(self, *args) | Erase key-value represented fields.
:rtype: DataFrame
:Example:
>>> new_ds = df.erase_key_value('f1 f2') | 12.232648 | 13.621741 | 0.898024 |
field_roles = dict((k, v.name if isinstance(v, SequenceExpr) else v)
for k, v in six.iteritems(field_roles))
self._assert_ml_fields_valid(*list(six.itervalues(field_roles)))
field_roles = dict((_get_field_name(f), MLField.translate_role_name(role))
... | def roles(self, clear_features=True, **field_roles) | Set roles of fields
:param clear_features: Clear feature roles on fields
:param field_roles:
:return: | 4.386209 | 4.633972 | 0.946533 |
from .. import preprocess
split_obj = getattr(preprocess, '_Split')(fraction=frac)
return split_obj.transform(self) | def split(self, frac) | Split the DataFrame into two DataFrames with certain ratio.
:param frac: Split ratio
:type frac: float
:return: two split DataFrame objects
:rtype: list[DataFrame] | 10.974541 | 13.474168 | 0.814487 |
from .. import preprocess
if id_col_name in self.schema:
raise ValueError('ID column collides with existing columns.')
append_id_obj = getattr(preprocess, '_AppendID')(id_col=id_col_name, selected_cols=cols)
return append_id_obj.transform(self) | def append_id(self, id_col_name='append_id', cols=None) | Append an ID column to current DataFrame.
:param str id_col_name: name of appended ID field.
:param str cols: fields contained in output. All fields by default.
:return: DataFrame with ID field
:rtype: DataFrame | 5.267977 | 5.257524 | 1.001988 |
field_name = self.name
new_df = copy_df(self)
new_df._perform_operation(op.FieldContinuityOperation({field_name: True}))
return new_df | def continuous(self) | Set sequence to be continuous.
:rtype: Column
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=DISCRETE, f2=DISCRETE
>>> # Now we want to set ``f1`` and ``f2`` into continuous
>>> new_ds = df.continuous('f1 f2') | 10.297642 | 10.001741 | 1.029585 |
field_name = self.name
new_df = copy_df(self)
new_df._perform_operation(op.FieldContinuityOperation({field_name: False}))
return new_df | def discrete(self) | Set sequence to be discrete.
:rtype: Column
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuous
>>> new_ds = df.discrete('f1 f2') | 11.745683 | 11.403882 | 1.029972 |
field_name = self.name
new_df = copy_df(self)
new_df._perform_operation(op.FieldKVConfigOperation({field_name: KVConfig(**kwargs)}))
return new_df | def key_value(self, **kwargs) | Set fields to be key-value represented.
:rtype: Column
:Example:
>>> new_ds = df.key_value('f1 f2', kv=':', item=',') | 11.889757 | 12.311172 | 0.96577 |
field_name = self.name
new_df = copy_df(self)
new_df._perform_operation(op.FieldKVConfigOperation({field_name: None}))
return new_df | def erase_key_value(self) | Erase key-value represented fields.
:rtype: Column
:Example:
>>> new_ds = df.erase_key_value('f1 f2') | 13.464006 | 14.946959 | 0.900786 |
field_name = self.name
field_roles = {field_name: MLField.translate_role_name(role_name)}
if field_roles:
return _change_singleton_roles(self, field_roles, True)
else:
return self | def role(self, role_name) | Set role of current column
:param role_name: name of the role to be selected.
:return: | 7.674399 | 8.399724 | 0.913649 |
self._init_attr('_deps', None)
self._init_attr('_ban_optimize', False)
self._init_attr('_engine', None)
self._init_attr('_Expr__execution', None)
self._init_attr('_need_cache', False)
self._init_attr('_mem_cache', False)
if '_id' not in kwargs:
... | def _init(self, *args, **kwargs) | _deps is used for common dependencies.
When a expr depend on other exprs, and the expr is not calculated from the others,
the _deps are specified to identify the dependencies. | 4.915107 | 4.109145 | 1.196139 |
_wrapper = kwargs.pop('wrapper', None)
def wrapper(result):
self.__execution = result
if _wrapper is not None:
return _wrapper(result)
else:
return result
return self._handle_delay_call('execute', self, wrapper=wrappe... | def execute(self, **kwargs) | :param hints: settings for SQL, e.g. `odps.sql.mapper.split.size`
:type hints: dict
:param priority: instance priority, 9 as default
:type priority: int
:param running_cluster: cluster to run this instance
:return: execution result
:rtype: :class:`odps.df.backends.frame.R... | 5.604919 | 5.745444 | 0.975542 |
from ..engines import get_default_engine
engine = get_default_engine(self)
return engine.compile(self) | def compile(self) | Compile this expression into an ODPS SQL
:return: compiled DAG
:rtype: str | 7.604438 | 6.828933 | 1.113562 |
if lifecycle is None and options.lifecycle is not None:
lifecycle = \
options.lifecycle if not name.startswith(TEMP_TABLE_PREFIX) \
else options.temp_lifecycle
return self._handle_delay_call('persist', self, name, partitions=partitions, partition... | def persist(self, name, partitions=None, partition=None, lifecycle=None, project=None, **kwargs) | Persist the execution into a new table. If `partitions` not specified,
will create a new table without partitions if the table does not exist,
and insert the SQL result into it.
If `partitions` are specified, they will be the partition fields of the new table.
If `partition` is specified... | 4.933286 | 6.555415 | 0.752551 |
from .query import CollectionVisitor
if not isinstance(expr, six.string_types):
raise ValueError('expr must be a string')
frame = sys._getframe(2).f_locals
try:
env = frame.copy()
finally:
del frame
visitor = CollectionVisit... | def query(self, expr) | Query the data with a boolean expression.
:param expr: the query string, you can use '@' character refer to environment variables.
:return: new collection
:rtype: :class:`odps.df.expr.expressions.CollectionExpr` | 4.790039 | 4.983627 | 0.961155 |
predicates = self._get_fields(predicates)
predicate = reduce(operator.and_, predicates)
return FilterCollectionExpr(self, predicate, _schema=self._schema) | def filter(self, *predicates) | Filter the data by predicates
:param predicates: the conditions to filter
:return: new collection
:rtype: :class:`odps.df.expr.expressions.CollectionExpr` | 9.700188 | 9.92483 | 0.977366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.