_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q267700 | ABweb._login | test | def _login(self, username, password):
'''login and update cached cookies'''
self.logger.debug('login ...')
res = self.session.http.get(self.login_url)
input_list = self._input_re.findall(res.text)
if not input_list:
raise PluginError('Missing input data on login website.')
data = {}
for _input_data in input_list:
try:
_input_name = self._name_re.search(_input_data).group(1)
except AttributeError:
continue
try:
_input_value = self._value_re.search(_input_data).group(1)
except AttributeError:
_input_value = ''
data[_input_name] = _input_value
login_data = {
'ctl00$Login1$UserName': username,
'ctl00$Login1$Password': password,
'ctl00$Login1$LoginButton.x': '0',
'ctl00$Login1$LoginButton.y': '0'
}
data.update(login_data)
res = | python | {
"resource": ""
} |
q267701 | StreamMapper.map | test | def map(self, key, func, *args, **kwargs):
"""Creates a key-function mapping.
The return value from the function should be either
- A tuple containing a name and stream
- A iterator of tuples containing a name and stream
| python | {
"resource": ""
} |
q267702 | CrunchyrollAPI._api_call | test | def _api_call(self, entrypoint, params=None, schema=None):
"""Makes a call against the api.
:param entrypoint: API method to call.
:param params: parameters to include in the request data.
:param schema: schema to use to validate the data
"""
url = self._api_url.format(entrypoint)
# Default params
params = params or {}
if self.session_id:
params.update({
"session_id": self.session_id
})
else:
params.update({
"device_id": self.device_id,
"device_type": self._access_type,
| python | {
"resource": ""
} |
q267703 | CrunchyrollAPI.start_session | test | def start_session(self):
"""
Starts a session against Crunchyroll's server.
Is recommended that you call this method before making any other calls
to make sure you have a valid session against the server.
"""
params = {}
if self.auth:
| python | {
"resource": ""
} |
q267704 | CrunchyrollAPI.get_info | test | def get_info(self, media_id, fields=None, schema=None):
"""
Returns the data for a certain media item.
:param media_id: id that identifies the media item to be accessed.
:param fields: list of the media"s field to be returned. By default the
API returns some fields, but others are not | python | {
"resource": ""
} |
q267705 | Crunchyroll._create_api | test | def _create_api(self):
"""Creates a new CrunchyrollAPI object, initiates it's session and
tries to authenticate it either by using saved credentials or the
user's username and password.
"""
if self.options.get("purge_credentials"):
self.cache.set("session_id", None, 0)
self.cache.set("auth", None, 0)
self.cache.set("session_id", None, 0)
# use the crunchyroll locale as an override, for backwards compatibility
locale = self.get_option("locale") or self.session.localization.language_code
api = CrunchyrollAPI(self.cache,
self.session,
session_id=self.get_option("session_id"),
locale=locale)
if not self.get_option("session_id"):
self.logger.debug("Creating session with locale: {0}", locale)
api.start_session()
if api.auth:
self.logger.debug("Using saved credentials")
login = api.authenticate()
self.logger.info("Successfully logged in as '{0}'",
login["user"]["username"] or login["user"]["email"])
| python | {
"resource": ""
} |
q267706 | compress | test | def compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0):
"""Compress a byte string.
Args:
string (bytes): The input data.
mode (int, optional): The compression mode can be MODE_GENERIC (default),
MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0).
quality (int, optional): Controls the compression-speed vs compression-
density tradeoff. The higher the quality, the slower the compression.
Range is 0 to 11. Defaults to 11.
lgwin (int, optional): Base 2 logarithm of the sliding window size. Range
is 10 to 24. Defaults to 22.
lgblock (int, optional): Base 2 logarithm of the maximum input block size.
| python | {
"resource": ""
} |
q267707 | outputCharFormatter | test | def outputCharFormatter(c):
"""Show character in readable format
"""
#TODO 2: allow hex only output
if 32<c<127: return chr(c)
elif c==10: return '\\n'
| python | {
"resource": ""
} |
q267708 | outputFormatter | test | def outputFormatter(s):
"""Show string or char.
"""
result = ''
def formatSubString(s):
for c in s:
if c==32: yield ' '
else: yield outputCharFormatter(c)
| python | {
"resource": ""
} |
q267709 | BitStream.readBytes | test | def readBytes(self, n):
"""Read n bytes from the stream on a byte boundary.
"""
if self.pos&7: raise | python | {
"resource": ""
} |
q267710 | Symbol.value | test | def value(self, extra=None):
"""The value used for processing. Can be a tuple.
with optional extra bits
"""
if isinstance(self.code, WithExtra):
if not 0<=extra<1<<self.extraBits():
raise ValueError("value: extra value doesn't fit in extraBits")
| python | {
"resource": ""
} |
q267711 | Symbol.explanation | test | def explanation(self, extra=None):
"""Long explanation of the value from the numeric value
with optional extra bits
Used by Layout.verboseRead when printing the value
| python | {
"resource": ""
} |
q267712 | PrefixDecoder.setDecode | test | def setDecode(self, decodeTable):
"""Store decodeTable,
and compute lengthTable, minLength, maxLength from encodings.
"""
self.decodeTable = decodeTable
#set of symbols with unknown length
todo = set(decodeTable)
#bit size under investigation
maskLength = 0
lengthTable = {}
while todo:
mask = (1<<maskLength)-1
#split the encodings that we didn't find yet using b bits
| python | {
"resource": ""
} |
q267713 | PrefixDecoder.setLength | test | def setLength(self, lengthTable):
"""Given the bit pattern lengths for symbols given in lengthTable,
set decodeTable, minLength, maxLength
"""
self.lengthTable = lengthTable
self.minLength = min(lengthTable.values())
self.maxLength = max(lengthTable.values())
#compute the backwards codes first; then reverse them
#compute (backwards) first code for every separate lengths
nextCodes = []
#build codes for each length, from right to left
code = 0
for bits in range(self.maxLength+1):
code <<= 1
| python | {
"resource": ""
} |
q267714 | Code.showCode | test | def showCode(self, width=80):
"""Show all words of the code in a nice format.
"""
#make table of all symbols with binary strings
symbolStrings = [
(self.bitPattern(s.index), self.mnemonic(s.index))
for s in self
]
#determine column widths the way Lisp programmers do it
leftColWidth, rightColWidth = map(max, map(
map,
repeat(len),
zip(*symbolStrings)
))
| python | {
"resource": ""
} |
q267715 | Code.readTuple | test | def readTuple(self, stream):
"""Read symbol from stream. Returns symbol, length.
| python | {
"resource": ""
} |
q267716 | WithExtra.explanation | test | def explanation(self, index, extra=None):
"""Expanded version of Code.explanation supporting extra bits.
If you don't supply extra, it is not mentioned.
"""
extraBits = 0 if extra is None else self.extraBits(index)
if not hasattr(self, 'extraTable'):
formatString = '{0}{3}'
lo = hi = value = self.value(index, extra)
elif extraBits==0:
formatString = '{0}{2}: {3}'
lo, hi = self.span(index)
value = lo
else:
| python | {
"resource": ""
} |
q267717 | Enumerator.value | test | def value(self, index, extra):
"""Override if you don't define value0 and extraTable
"""
lower, upper = self.span(index)
value = lower+(extra or 0)
| python | {
"resource": ""
} |
q267718 | Enumerator.span | test | def span(self, index):
"""Give the range of possible values in a tuple
Useful for mnemonic and explanation
"""
lower | python | {
"resource": ""
} |
q267719 | TreeAlphabet.value | test | def value(self, index, extra):
"""Give count and value."""
index = index
if index==0: return 1, 0
| python | {
"resource": ""
} |
q267720 | InsertAndCopyAlphabet.mnemonic | test | def mnemonic(self, index):
"""Make a nice mnemonic
"""
i,c,d0 = self.splitSymbol(index)
iLower, _ = i.code.span(i.index)
iExtra = i.extraBits()
cLower, _ = c.code.span(c.index)
| python | {
"resource": ""
} |
q267721 | DistanceAlphabet.mnemonic | test | def mnemonic(self, index, verbose=False):
"""Give mnemonic representation of meaning.
verbose compresses strings of x's
"""
if index<16:
return ['last', '2last', '3last', '4last',
'last-1', 'last+1', 'last-2', 'last+2', 'last-3', 'last+3',
'2last-1', '2last+1', '2last-2', '2last+2', '2last-3', '2last+3'
][index]
if index<16+self.NDIRECT:
return str(index-16)
#construct strings like "1xx01-15"
index -= self.NDIRECT+16
hcode = index >> self.NPOSTFIX
| python | {
"resource": ""
} |
q267722 | WordList.compileActions | test | def compileActions(self):
"""Build the action table from the text above
"""
import re
self.actionList = actions = [None]*121
#Action 73, which is too long, looks like this when expanded:
actions[73] = "b' the '+w+b' of the '"
#find out what the columns are
actionLines = self.actionTable.splitlines()
colonPositions = [m.start()
for m in re.finditer(':',actionLines[1])
]+[100]
columns = [(colonPositions[i]-3,colonPositions[i+1]-3)
for i in range(len(colonPositions)-1)]
for line in self.actionTable.splitlines(keepends=False):
for start,end in columns:
action = line[start:end]
#skip empty actions
if not action or action.isspace(): continue
#chop it up, and check if the colon is properly placed
index, colon, action = action[:3], action[3], action[4:]
assert colon==':'
#remove filler spaces at right
action = action.rstrip()
#replace space symbols
action = | python | {
"resource": ""
} |
q267723 | WordList.doAction | test | def doAction(self, w, action):
"""Perform the proper action
"""
#set environment for the UpperCaseFirst
U = | python | {
"resource": ""
} |
q267724 | Layout.makeHexData | test | def makeHexData(self, pos):
"""Produce hex dump of all data containing the bits
from pos to stream.pos
| python | {
"resource": ""
} |
q267725 | Layout.processStream | test | def processStream(self):
"""Process a brotli stream.
"""
print('addr hex{:{}s}binary context explanation'.format(
'', self.width-10))
print('Stream header'.center(60, '-'))
self.windowSize = self.verboseRead(WindowSizeAlphabet())
print('Metablock header'.center(60, '='))
self.ISLAST = False
self.output = bytearray()
while not self.ISLAST:
self.ISLAST = self.verboseRead(
BoolCode('LAST', description="Last block"))
if self.ISLAST:
if self.verboseRead(
BoolCode('EMPTY', description="Empty block")): break
if self.metablockLength(): continue
if not self.ISLAST and self.uncompressed(): continue
print('Block type descriptors'.center(60, '-'))
self.numberOfBlockTypes = {}
self.currentBlockCounts = {}
self.blockTypeCodes = {}
self.blockCountCodes = {}
for blockType in (L,I,D): self.blockType(blockType)
print('Distance code parameters'.center(60, '-'))
self.NPOSTFIX, self.NDIRECT = self.verboseRead(DistanceParamAlphabet())
| python | {
"resource": ""
} |
q267726 | Layout.metablockLength | test | def metablockLength(self):
"""Read MNIBBLES and meta block length;
if empty block, skip block and return true.
"""
self.MLEN = self.verboseRead(MetablockLengthAlphabet())
if self.MLEN:
return False
#empty block; skip and return False
self.verboseRead(ReservedAlphabet())
| python | {
"resource": ""
} |
q267727 | Layout.uncompressed | test | def uncompressed(self):
"""If true, handle uncompressed data
"""
ISUNCOMPRESSED = self.verboseRead(
BoolCode('UNCMPR', description='Is uncompressed?'))
if ISUNCOMPRESSED:
self.verboseRead(FillerAlphabet(streamPos=self.stream.pos))
print('Uncompressed data:')
| python | {
"resource": ""
} |
q267728 | Layout.blockType | test | def blockType(self, kind):
"""Read block type switch descriptor for given kind of blockType."""
NBLTYPES = self.verboseRead(TypeCountAlphabet(
'BT#'+kind[0].upper(),
description='{} block types'.format(kind),
))
self.numberOfBlockTypes[kind] = NBLTYPES
if NBLTYPES>=2:
self.blockTypeCodes[kind] = self.readPrefixCode(
| python | {
"resource": ""
} |
q267729 | Layout.IMTF | test | def IMTF(v):
"""In place inverse move to front transform.
"""
#mtf is initialized virtually with range(infinity)
mtf = []
for i, vi in enumerate(v):
#get old value from mtf. If never seen, take virtual value
try: | python | {
"resource": ""
} |
q267730 | Layout.readPrefixArray | test | def readPrefixArray(self, kind, numberOfTrees):
"""Read prefix code array"""
prefixes = []
for i in range(numberOfTrees):
if kind==L: alphabet = LiteralAlphabet(i)
elif kind==I: alphabet = InsertAndCopyAlphabet(i)
elif kind==D: alphabet = DistanceAlphabet(
| python | {
"resource": ""
} |
q267731 | monochrome | test | def monochrome(I, color, vmin=None, vmax=None):
"""Turns a intensity array to a monochrome 'image' by replacing each intensity by a scaled 'color'
Values in I between vmin and vmax get scaled between 0 and 1, and values outside this range are clipped to this.
Example
>>> I = np.arange(16.).reshape(4,4)
>>> color = (0, 0, 1) # red
>>> rgb = vx.image.monochrome(I, color) # shape is (4,4,3)
:param I: ndarray of any shape (2d for image)
:param color: sequence of a (r, g and b) value | python | {
"resource": ""
} |
q267732 | polychrome | test | def polychrome(I, colors, vmin=None, vmax=None, axis=-1):
"""Similar to monochrome, but now do it for multiple colors
Example
>>> I = np.arange(32.).reshape(4,4,2)
>>> colors = [(0, 0, 1), (0, 1, 0)] # red and green
>>> rgb = vx.image.polychrome(I, colors) # shape is (4,4,3)
:param I: ndarray of any shape (3d will result in a 2d image)
:param colors: sequence of [(r,g,b), ...] values
:param vmin: normalization minimum for | python | {
"resource": ""
} |
q267733 | arrow_table_from_vaex_df | test | def arrow_table_from_vaex_df(ds, column_names=None, selection=None, strings=True, virtual=False):
"""Implementation of Dataset.to_arrow_table"""
names = []
arrays = []
for name, array in ds.to_items(column_names=column_names, selection=selection, strings=strings, virtual=virtual):
| python | {
"resource": ""
} |
q267734 | patch | test | def patch(f):
'''Adds method f to the Dataset class'''
name = f.__name__
| python | {
"resource": ""
} |
q267735 | add_virtual_columns_cartesian_velocities_to_pmvr | test | def add_virtual_columns_cartesian_velocities_to_pmvr(self, x="x", y="y", z="z", vx="vx", vy="vy", vz="vz", vr="vr", pm_long="pm_long", pm_lat="pm_lat", distance=None):
"""Concert velocities from a cartesian system to proper motions and radial velocities
TODO: errors
:param x: name of x column (input)
:param y: y
:param z: z
:param vx: vx
:param vy: vy
:param vz: vz
:param vr: name of the column for the radial velocity in the r direction (output)
:param pm_long: name of the column for the proper motion component in the longitude direction (output)
:param pm_lat: name of the column for the proper motion component in the latitude direction, positive points to the north pole (output)
:param distance: Expression for distance, if not given defaults to sqrt(x**2+y**2+z**2), but if this column already exists, passing this expression may lead to a better performance
:return:
"""
| python | {
"resource": ""
} |
q267736 | add_virtual_columns_proper_motion2vperpendicular | test | def add_virtual_columns_proper_motion2vperpendicular(self, distance="distance", pm_long="pm_l", pm_lat="pm_b",
vl="vl", vb="vb",
propagate_uncertainties=False,
radians=False):
"""Convert proper motion to perpendicular velocities.
:param distance:
:param pm_long:
:param pm_lat:
:param vl:
:param vb:
:param cov_matrix_distance_pm_long_pm_lat:
:param uncertainty_postfix:
:param covariance_postfix:
:param radians:
:return:
"""
k = 4.74057 | python | {
"resource": ""
} |
q267737 | Expression._graphviz | test | def _graphviz(self, dot=None):
"""Return a graphviz.Digraph object with a graph of the expression"""
from graphviz import Graph, Digraph
node = self._graph()
dot = dot or Digraph(comment=self.expression)
def walk(node):
if isinstance(node, six.string_types):
dot.node(node, node)
return node, node
else:
node_repr, fname, fobj, deps = node
| python | {
"resource": ""
} |
q267738 | Expression.value_counts | test | def value_counts(self, dropna=False, dropnull=True, ascending=False, progress=False):
"""Computes counts of unique values.
WARNING:
* If the expression/column is not categorical, it will be converted on the fly
* dropna is False by default, it is True by default in pandas
:param dropna: when True, it will not report the missing values
:param ascending: when False (default) it will report the most frequent occuring item first
:returns: Pandas series containing the counts
"""
from pandas import Series
dtype = self.dtype
transient = self.transient or self.ds.filtered or self.ds.is_masked(self.expression)
if self.dtype == str_type and not transient:
# string is a special case, only ColumnString are not transient
ar = self.ds.columns[self.expression]
if not isinstance(ar, ColumnString):
transient = True
counter_type = counter_type_from_dtype(self.dtype, transient)
counters = [None] * self.ds.executor.thread_pool.nthreads
def map(thread_index, i1, i2, ar):
if counters[thread_index] is None:
counters[thread_index] = counter_type()
if dtype == str_type:
previous_ar = ar
ar = _to_string_sequence(ar)
if not transient:
assert ar is previous_ar.string_sequence
if np.ma.isMaskedArray(ar):
mask = np.ma.getmaskarray(ar)
counters[thread_index].update(ar, mask)
else:
counters[thread_index].update(ar)
return 0
def reduce(a, b):
return a+b
self.ds.map_reduce(map, reduce, [self.expression], delay=False, progress=progress, name='value_counts', info=True, to_numpy=False)
counters = [k for k in counters if k is not None] | python | {
"resource": ""
} |
q267739 | Expression.map | test | def map(self, mapper, nan_mapping=None, null_mapping=None):
"""Map values of an expression or in memory column accoring to an input
dictionary or a custom callable function.
Example:
>>> import vaex
>>> df = vaex.from_arrays(color=['red', 'red', 'blue', 'red', 'green'])
>>> mapper = {'red': 1, 'blue': 2, 'green': 3}
>>> df['color_mapped'] = df.color.map(mapper)
>>> df
# color color_mapped
0 red 1
1 red 1
2 blue 2
3 red 1
4 green 3
>>> import numpy as np
>>> df = vaex.from_arrays(type=[0, 1, 2, 2, 2, np.nan])
>>> df['role'] = df['type'].map({0: 'admin', 1: 'maintainer', 2: 'user', np.nan: 'unknown'})
>>> df
# type role
0 0 admin
1 1 maintainer
2 2 user
3 2 user
4 2 user
5 nan unknown
:param mapper: dict like object used to map the values from keys to values
:param nan_mapping: value to be used when a nan is present (and not in the mapper)
:param null_mapping: value to use used when there is a missing value
:return: A vaex expression
:rtype: vaex.expression.Expression
"""
assert isinstance(mapper, collectionsAbc.Mapping), "mapper should be a dict like object"
df = self.ds
mapper_keys = np.array(list(mapper.keys()))
# we map the keys to a ordinal values [0, N-1] using the set
key_set = df._set(self.expression)
| python | {
"resource": ""
} |
q267740 | app | test | def app(*args, **kwargs):
"""Create a vaex app, the QApplication mainloop must be started.
In ipython notebook/jupyter do the following:
>>> import vaex.ui.main # this causes the qt api level to be set properly
>>> import vaex
Next cell:
>>> %gui qt
| python | {
"resource": ""
} |
q267741 | open_many | test | def open_many(filenames):
"""Open a list of filenames, and return a DataFrame with all DataFrames cocatenated.
:param list[str] filenames: list of filenames/paths
:rtype: DataFrame
"""
dfs = []
for filename in filenames:
filename = | python | {
"resource": ""
} |
q267742 | from_samp | test | def from_samp(username=None, password=None):
"""Connect to a SAMP Hub and wait for a single table load event, disconnect, download the table and return the DataFrame.
Useful if you | python | {
"resource": ""
} |
q267743 | from_astropy_table | test | def from_astropy_table(table):
"""Create a vaex DataFrame from an Astropy Table."""
import vaex.file.other
| python | {
"resource": ""
} |
q267744 | from_arrays | test | def from_arrays(**arrays):
"""Create an in memory DataFrame from numpy arrays.
Example
>>> import vaex, numpy as np
>>> x = np.arange(5)
>>> y = x ** 2
>>> vaex.from_arrays(x=x, y=y)
# x y
0 0 0
1 1 1
2 2 4
3 3 9
4 4 16
>>> some_dict = {'x': x, 'y': y}
>>> vaex.from_arrays(**some_dict) # in case you have your columns | python | {
"resource": ""
} |
q267745 | from_scalars | test | def from_scalars(**kwargs):
"""Similar to from_arrays, but convenient for a DataFrame of length 1.
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
:rtype: | python | {
"resource": ""
} |
q267746 | from_pandas | test | def from_pandas(df, name="pandas", copy_index=True, index_name="index"):
"""Create an in memory DataFrame from a pandas DataFrame.
:param: pandas.DataFrame df: Pandas DataFrame
:param: name: unique for the DataFrame
>>> import vaex, pandas as pd
>>> df_pandas = pd.from_csv('test.csv')
>>> df = vaex.from_pandas(df_pandas)
:rtype: DataFrame
"""
import six
vaex_df = vaex.dataframe.DataFrameArrays(name)
def add(name, column):
values = column.values
try:
vaex_df.add_column(name, values)
except Exception as e:
print("could not convert column %s, error: %r, | python | {
"resource": ""
} |
q267747 | from_csv | test | def from_csv(filename_or_buffer, copy_index=True, **kwargs):
"""Shortcut to read a csv file using pandas and convert to a DataFrame directly.
:rtype: DataFrame
"""
| python | {
"resource": ""
} |
q267748 | server | test | def server(url, **kwargs):
"""Connect to hostname supporting the vaex web api.
:param str hostname: hostname or ip address of server
:return vaex.dataframe.ServerRest: returns a server object, note that it does not connect to the server yet, so this will always succeed
| python | {
"resource": ""
} |
q267749 | zeldovich | test | def zeldovich(dim=2, N=256, n=-2.5, t=None, scale=1, seed=None):
"""Creates a zeldovich DataFrame. | python | {
"resource": ""
} |
q267750 | concat | test | def concat(dfs):
'''Concatenate a list of DataFrames.
| python | {
"resource": ""
} |
q267751 | vrange | test | def vrange(start, stop, step=1, dtype='f8'):
"""Creates a virtual column which is the equivalent of numpy.arange, but uses 0 memory"""
| python | {
"resource": ""
} |
q267752 | VaexApp.open | test | def open(self, path):
"""Add a dataset and add it to the UI"""
logger.debug("open dataset: %r", path)
if path.startswith("http") or path.startswith("ws"):
dataset = vaex.open(path, thread_mover=self.call_in_main_thread)
else:
| python | {
"resource": ""
} |
q267753 | DatasetRest.evaluate | test | def evaluate(self, expression, i1=None, i2=None, out=None, selection=None, delay=False):
expression = _ensure_strings_from_expressions(expression)
"""basic support for evaluate at server, at least to run some unittest, do not expect this to work from strings"""
| python | {
"resource": ""
} |
q267754 | delayed | test | def delayed(f):
'''Decorator to transparantly accept delayed computation.
Example:
>>> delayed_sum = ds.sum(ds.E, binby=ds.x, limits=limits,
>>> shape=4, delay=True)
>>> @vaex.delayed
>>> def total_sum(sums):
>>> return sums.sum()
>>> sum_of_sums = total_sum(delayed_sum)
>>> ds.execute()
>>> sum_of_sums.get()
See the tutorial for a more complete example https://docs.vaex.io/en/latest/tutorial.html#Parallel-computations
'''
def wrapped(*args, **kwargs):
# print "calling", f, "with", kwargs
# key_values = kwargs.items()
key_promise = list([(key, promisify(value)) for key, value in kwargs.items()])
# key_promise = [(key, promisify(value)) for key, value in key_values]
arg_promises = list([promisify(value) for value in args])
kwarg_promises = list([promise for key, promise in key_promise])
promises = arg_promises + kwarg_promises
for promise in promises:
def echo_error(exc, promise=promise):
print("error with ", promise, "exception is", exc)
# raise exc
def echo(value, | python | {
"resource": ""
} |
q267755 | Selection._depending_columns | test | def _depending_columns(self, ds):
'''Find all columns that this selection depends on for df ds'''
depending = set()
for expression in self.expressions:
expression = ds._expr(expression) # make sure it is an expression
depending | python | {
"resource": ""
} |
q267756 | SubspaceLocal._task | test | def _task(self, task, progressbar=False):
"""Helper function for returning tasks results, result when immediate is True, otherwise the task itself, which is a promise"""
if self.delay:
# should return a task or a promise nesting it
return self.executor.schedule(task)
else:
import vaex.utils
callback = None
try:
if progressbar == True:
def update(fraction):
| python | {
"resource": ""
} |
q267757 | ____RankingTableModel.sort | test | def sort(self, Ncol, order):
"""Sort table by given column number.
"""
self.emit(QtCore.SIGNAL("layoutAboutToBeChanged()"))
if Ncol == 0:
print("by name")
# get indices, sorted by pair name
sortlist = list(zip(self.pairs, list(range(len(self.pairs)))))
print(sortlist)
sortlist.sort(key=operator.itemgetter(0))
print(sortlist)
self.indices = list(map(operator.itemgetter(1), sortlist))
print((self.indices))
if Ncol == 1:
# get indices, sorted by ranking, or no sorting
if None not in self.ranking:
| python | {
"resource": ""
} |
q267758 | getinfo | test | def getinfo(filename, seek=None):
"""Read header data from Gadget data file 'filename' with Gadget file
type 'gtype'. Returns offsets of positions and velocities."""
DESC = '=I4sII' # struct formatting string
HEAD = '=I6I6dddii6iiiddddii6ii60xI' # struct formatting string
keys = ('Npart', 'Massarr', 'Time', 'Redshift', 'FlagSfr', 'FlagFeedback', 'Nall', 'FlagCooling', 'NumFiles', 'BoxSize', 'Omega0', 'OmegaLambda', 'HubbleParam', 'FlagAge', 'FlagMetals', 'NallHW', 'flag_entr_ics', 'filename')
f = open(filename, 'rb')
"""Detects Gadget file type (type 1 or 2; resp. without or with the 16
byte block headers)."""
firstbytes = struct.unpack('I',f.read(4))
if firstbytes[0] == 8:
gtype = 2
else:
gtype = 1
if gtype == 2:
f.seek(16)
else:
f.seek(0)
if seek is not None:
f.seek(seek)
raw = | python | {
"resource": ""
} |
q267759 | Slicer.clear | test | def clear(self, event):
"""clear the cursor"""
if self.useblit:
self.background = (
self.canvas.copy_from_bbox(self.canvas.figure.bbox))
for line in | python | {
"resource": ""
} |
q267760 | PlotDialog._wait | test | def _wait(self):
"""Used for unittesting to make sure the plots are all done"""
logger.debug("will wait for last plot to finish")
self._plot_event = threading.Event()
self.queue_update._wait()
self.queue_replot._wait()
self.queue_redraw._wait()
qt_app = QtCore.QCoreApplication.instance()
sleep = 10
| python | {
"resource": ""
} |
q267761 | os_open | test | def os_open(document):
"""Open document by the default handler of the OS, could be a url opened by a browser, a text file by an editor etc"""
osname = platform.system().lower()
if osname == "darwin":
os.system("open \"" + document + "\"")
if osname == "linux":
| python | {
"resource": ""
} |
q267762 | write_to | test | def write_to(f, mode):
"""Flexible writing, where f can be a filename or f object, if filename, closed after writing"""
if hasattr(f, 'write'):
| python | {
"resource": ""
} |
q267763 | _split_and_combine_mask | test | def _split_and_combine_mask(arrays):
'''Combines all masks from a list of arrays, and logically ors them into a single mask'''
masks = [np.ma.getmaskarray(block) for block | python | {
"resource": ""
} |
q267764 | DataFrame.nop | test | def nop(self, expression, progress=False, delay=False):
"""Evaluates expression, and drop the result, usefull for benchmarking, since vaex is usually lazy"""
expression = _ensure_string_from_expression(expression)
def map(ar):
pass
| python | {
"resource": ""
} |
q267765 | DataFrame.first | test | def first(self, expression, order_expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None):
"""Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`.
Example:
>>> import vaex
>>> df = vaex.example()
>>> df.first(df.x, df.y, shape=8)
>>> df.first(df.x, df.y, shape=8, binby=[df.y])
>>> df.first(df.x, df.y, shape=8, binby=[df.y])
array([-4.81883764, 11.65378 , 9.70084476, -7.3025589 , 4.84954977,
8.47446537, -5.73602629, 10.18783 ])
:param expression: The value to be placed in the bin.
:param order_expression: Order the values in the bins by this expression.
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
| python | {
"resource": ""
} |
q267766 | DataFrame.mean | test | def mean(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False):
"""Calculate the mean for expression, possibly on a grid defined by binby.
Example:
>>> df.mean("x")
-0.067131491264005971
>>> df.mean("(x**2+y**2)**0.5", binby="E", shape=4)
array([ 2.43483742, 4.41840721, 8.26742458, 15.53846476])
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
:param delay: {delay}
:param progress: {progress}
:return: {return_stat_scalar}
"""
return self._compute_agg('mean', expression, binby, limits, shape, selection, delay, edges, progress)
logger.debug("mean of %r, with binby=%r, limits=%r, shape=%r, selection=%r, delay=%r", | python | {
"resource": ""
} |
q267767 | DataFrame.sum | test | def sum(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False):
"""Calculate the sum for the given expression, possible on a grid defined by binby
Example:
>>> df.sum("L")
304054882.49378014
>>> df.sum("L", binby="E", shape=4)
array([ 8.83517994e+06, 5.92217598e+07, 9.55218726e+07,
1.40008776e+08])
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
:param delay: {delay}
:param progress: {progress}
:return: {return_stat_scalar}
"""
return self._compute_agg('sum', expression, binby, limits, shape, selection, delay, edges, progress)
@delayed
def finish(*sums): | python | {
"resource": ""
} |
q267768 | DataFrame.std | test | def std(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None):
"""Calculate the standard deviation for the given expression, possible on a grid defined by binby
>>> df.std("vz")
110.31773397535071
>>> df.std("vz", binby=["(x**2+y**2)**0.5"], shape=4)
array([ 123.57954851, 85.35190177, 61.14345748, 38.0740619 ])
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
:param delay: | python | {
"resource": ""
} |
q267769 | DataFrame.cov | test | def cov(self, x, y=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None):
"""Calculate the covariance matrix for x and y or more expressions, possibly on a grid defined by binby.
Either x and y are expressions, e.g:
>>> df.cov("x", "y")
Or only the x argument is given with a list of expressions, e,g.:
>>> df.cov(["x, "y, "z"])
Example:
>>> df.cov("x", "y")
array([[ 53.54521742, -3.8123135 ],
[ -3.8123135 , 60.62257881]])
>>> df.cov(["x", "y", "z"])
array([[ 53.54521742, -3.8123135 , -0.98260511],
[ -3.8123135 , 60.62257881, 1.21381057],
[ -0.98260511, 1.21381057, 25.55517638]])
>>> df.cov("x", "y", binby="E", shape=2)
array([[[ 9.74852878e+00, -3.02004780e-02],
[ -3.02004780e-02, 9.99288215e+00]],
[[ 8.43996546e+01, -6.51984181e+00],
[ -6.51984181e+00, 9.68938284e+01]]])
:param x: {expression}
:param y: {expression_single}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
:param delay: {delay}
:return: {return_stat_scalar}, the last dimensions are of shape (2,2)
"""
| python | {
"resource": ""
} |
q267770 | DataFrame.minmax | test | def minmax(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None):
"""Calculate the minimum and maximum for expressions, possibly on a grid defined by binby.
Example:
>>> df.minmax("x")
array([-128.293991, 271.365997])
>>> df.minmax(["x", "y"])
array([[-128.293991 , 271.365997 ],
[ -71.5523682, 146.465836 ]])
>>> df.minmax("x", binby="x", shape=5, limits=[-10, 10])
array([[-9.99919128, -6.00010443],
[-5.99972439, -2.00002384],
[-1.99991322, 1.99998057],
[ 2.0000093 , 5.99983597],
[ 6.0004878 , 9.99984646]])
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
:param delay: {delay}
:param progress: {progress}
:return: {return_stat_scalar}, the last dimension is of shape (2)
"""
# vmin = self._compute_agg('min', expression, binby, limits, shape, selection, delay, edges, progress)
# vmax = self._compute_agg('max', expression, binby, limits, shape, selection, delay, edges, progress)
@delayed
def finish(*minmax_list):
value = vaex.utils.unlistify(waslist, np.array(minmax_list))
value = value.astype(dtype0)
return value
@delayed
def calculate(expression, limits):
task = tasks.TaskStatistic(self, binby, shape, limits, weight=expression, op=tasks.OP_MIN_MAX, selection=selection)
| python | {
"resource": ""
} |
q267771 | DataFrame.min | test | def min(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False):
"""Calculate the minimum for given expressions, possibly on a grid defined by binby.
Example:
>>> df.min("x")
array(-128.293991)
>>> df.min(["x", "y"])
array([-128.293991 , -71.5523682])
>>> df.min("x", binby="x", shape=5, limits=[-10, 10])
array([-9.99919128, -5.99972439, -1.99991322, 2.0000093 , 6.0004878 ])
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
:param delay: {delay} | python | {
"resource": ""
} |
q267772 | DataFrame.median_approx | test | def median_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=256, percentile_limits="minmax", selection=False, delay=False):
"""Calculate the median , possibly on a grid defined by binby.
NOTE: this value is approximated by calculating the cumulative distribution on a grid defined by
percentile_shape and percentile_limits
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param percentile_limits: {percentile_limits}
:param percentile_shape: {percentile_shape}
| python | {
"resource": ""
} |
q267773 | DataFrame.plot_widget | test | def plot_widget(self, x, y, z=None, grid=None, shape=256, limits=None, what="count(*)", figsize=None,
f="identity", figure_key=None, fig=None, axes=None, xlabel=None, ylabel=None, title=None,
show=True, selection=[None, True], colormap="afmhot", grid_limits=None, normalize="normalize",
grid_before=None,
what_kwargs={}, type="default",
scales=None, tool_select=False, bq_cleanup=True,
backend="bqplot",
**kwargs):
"""Viz 1d, 2d or 3d in a Jupyter notebook
.. note::
This API is not fully settled and may change in the future
Example:
>>> df.plot_widget(df.x, df.y, backend='bqplot')
>>> df.plot_widget(df.pickup_longitude, df.pickup_latitude, backend='ipyleaflet')
:param backend: Widget backend to use: 'bqplot', 'ipyleaflet', 'ipyvolume', 'matplotlib'
"""
import vaex.jupyter.plot
backend = vaex.jupyter.plot.create_backend(backend)
cls | python | {
"resource": ""
} |
q267774 | DataFrame.healpix_count | test | def healpix_count(self, expression=None, healpix_expression=None, healpix_max_level=12, healpix_level=8, binby=None, limits=None, shape=default_shape, delay=False, progress=None, selection=None):
"""Count non missing value for expression on an array which represents healpix data.
:param expression: Expression or column for which to count non-missing values, or None or '*' for counting the rows
:param healpix_expression: {healpix_max_level}
:param healpix_max_level: {healpix_max_level}
:param healpix_level: {healpix_level}
:param binby: {binby}, these dimension follow the first healpix dimension.
:param limits: {limits}
:param shape: {shape}
:param selection: {selection}
:param delay: {delay}
:param progress: {progress}
:return:
"""
# if binby is None:
import healpy as hp
if healpix_expression is None:
if self.ucds.get("source_id", None) == 'meta.id;meta.main': # we now assume we have gaia data
healpix_expression = "source_id/34359738368"
if healpix_expression is None:
| python | {
"resource": ""
} |
q267775 | DataFrame.healpix_plot | test | def healpix_plot(self, healpix_expression="source_id/34359738368", healpix_max_level=12, healpix_level=8, what="count(*)", selection=None,
grid=None,
healpix_input="equatorial", healpix_output="galactic", f=None,
colormap="afmhot", grid_limits=None, image_size=800, nest=True,
figsize=None, interactive=False, title="", smooth=None, show=False, colorbar=True,
rotation=(0, 0, 0), **kwargs):
"""Viz data in 2d using a healpix column.
:param healpix_expression: {healpix_max_level}
:param healpix_max_level: {healpix_max_level}
:param healpix_level: {healpix_level}
:param what: {what}
:param selection: {selection}
:param grid: {grid}
:param healpix_input: Specificy if the healpix index is in "equatorial", "galactic" or "ecliptic".
:param healpix_output: Plot in "equatorial", "galactic" or "ecliptic".
:param f: function to apply to the data
:param colormap: matplotlib colormap
:param grid_limits: Optional sequence [minvalue, maxvalue] that determine the min and max value that map to the colormap (values below and above these are clipped to the the min/max). (default is [min(f(grid)), max(f(grid)))
:param image_size: size for the image that healpy uses for rendering
:param nest: If the healpix data is in nested (True) or ring (False)
:param figsize: If given, modify the matplotlib figure size. Example (14,9)
:param interactive: (Experimental, uses healpy.mollzoom is True)
:param title: Title of figure
:param smooth: apply gaussian smoothing, in degrees
:param show: Call matplotlib's show (True) or not (False, defaut)
:param rotation: Rotatate the plot, in format (lon, lat, psi) such that (lon, lat) is the center, and rotate on the screen by angle psi. All angles are degrees.
:return:
"""
# plot_level = healpix_level #healpix_max_level-reduce_level
import healpy as hp
import pylab as plt
if grid is None:
reduce_level = healpix_max_level - healpix_level
NSIDE = 2**healpix_level
nmax = hp.nside2npix(NSIDE)
# print nmax, np.sqrt(nmax)
scaling = 4**reduce_level
# print nmax
epsilon = 1. / scaling / 2
grid | python | {
"resource": ""
} |
q267776 | DataFrame.plot3d | test | def plot3d(self, x, y, z, vx=None, vy=None, vz=None, vwhat=None, limits=None, grid=None, what="count(*)", shape=128, selection=[None, True], f=None,
vcount_limits=None,
smooth_pre=None, smooth_post=None, grid_limits=None, normalize="normalize", colormap="afmhot",
figure_key=None, fig=None,
lighting=True, level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1,
show=True, **kwargs):
"""Use at own risk, requires ipyvolume"""
import vaex.ext.ipyvolume
# vaex.ext.ipyvolume.
cls = vaex.ext.ipyvolume.PlotDefault
plot3d = cls(df=self, x=x, y=y, z=z, vx=vx, vy=vy, vz=vz,
| python | {
"resource": ""
} |
q267777 | DataFrame.dtype | test | def dtype(self, expression, internal=False):
"""Return the numpy dtype for the given expression, if not a column, the first row will be evaluated to get the dtype."""
expression = _ensure_string_from_expression(expression)
if expression in self.variables:
return np.float64(1).dtype
elif expression in self.columns.keys():
column = self.columns[expression]
data = column[0:1]
dtype = data.dtype
else:
data = self.evaluate(expression, 0, 1, filtered=False)
| python | {
"resource": ""
} |
q267778 | DataFrame.get_private_dir | test | def get_private_dir(self, create=False):
"""Each DataFrame has a directory where files are stored for metadata etc.
Example
>>> import vaex
>>> ds = vaex.example()
>>> vaex.get_private_dir()
'/Users/users/breddels/.vaex/dfs/_Users_users_breddels_vaex-testing_data_helmi-dezeeuw-2000-10p.hdf5'
:param bool create: is True, it will create the directory if it does not exist
"""
if self.is_local():
name = os.path.abspath(self.path).replace(os.path.sep, "_")[:250] # should not be too long for most os'es
name = name.replace(":", "_") # for windows drive | python | {
"resource": ""
} |
q267779 | DataFrame.state_get | test | def state_get(self):
"""Return the internal state of the DataFrame in a dictionary
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
>>> df['r'] = (df.x**2 + df.y**2)**0.5
>>> df.state_get()
{'active_range': [0, 1],
'column_names': ['x', 'y', 'r'],
'description': None,
'descriptions': {},
'functions': {},
'renamed_columns': [],
'selections': {'__filter__': None},
'ucds': {},
'units': {},
'variables': {},
'virtual_columns': {'r': '(((x ** 2) + (y ** 2)) ** 0.5)'}}
"""
virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys())
units = {key: str(value) for key, value in self.units.items()}
ucds = {key: value for key, value in self.ucds.items() if key in virtual_names}
descriptions = {key: value for key, value in self.descriptions.items()}
import vaex.serialize
def check(key, value):
if not vaex.serialize.can_serialize(value.f):
warnings.warn('Cannot serialize function for virtual column {} (use vaex.serialize.register)'.format(key))
return False
return True
def clean(value):
return vaex.serialize.to_dict(value.f)
functions = {key: clean(value) for key, value in self.functions.items() if check(key, value)}
| python | {
"resource": ""
} |
q267780 | DataFrame.state_set | test | def state_set(self, state, use_active_range=False):
"""Sets the internal state of the df
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
>>> df
# x y r
0 1 2 2.23607
>>> df['r'] = (df.x**2 + df.y**2)**0.5
>>> state = df.state_get()
>>> state
{'active_range': [0, 1],
'column_names': ['x', 'y', 'r'],
'description': None,
'descriptions': {},
'functions': {},
'renamed_columns': [],
'selections': {'__filter__': None},
'ucds': {},
'units': {},
'variables': {},
'virtual_columns': {'r': '(((x ** 2) + (y ** 2)) ** 0.5)'}}
>>> df2 = vaex.from_scalars(x=3, y=4)
>>> df2.state_set(state) # now the virtual functions are 'copied'
>>> df2
# x y r
0 3 4 5
:param state: dict as returned by :meth:`DataFrame.state_get`.
:param bool use_active_range: Whether to use the active range or not.
"""
self.description = state['description']
if use_active_range:
self._index_start, self._index_end = state['active_range']
self._length_unfiltered = self._index_end - self._index_start
if 'renamed_columns' in state:
for old, new in state['renamed_columns']:
self._rename(old, new)
for name, value in state['functions'].items():
self.add_function(name, vaex.serialize.from_dict(value))
if 'column_names' in state:
# we clear all columns, and add them later on, since otherwise self[name] = ... will try
| python | {
"resource": ""
} |
q267781 | DataFrame.remove_virtual_meta | test | def remove_virtual_meta(self):
"""Removes the file with the virtual column etc, it does not change the current virtual columns etc."""
dir = self.get_private_dir(create=True)
path = os.path.join(dir, "virtual_meta.yaml")
try:
if os.path.exists(path):
| python | {
"resource": ""
} |
q267782 | DataFrame.write_virtual_meta | test | def write_virtual_meta(self):
"""Writes virtual columns, variables and their ucd,description and units.
The default implementation is to write this to a file called virtual_meta.yaml in the directory defined by
:func:`DataFrame.get_private_dir`. Other implementation may store this in the DataFrame file itself.
This method is called after virtual columns or variables are added. Upon opening a file, :func:`DataFrame.update_virtual_meta`
is called, so that the information is not lost between sessions.
Note: opening a DataFrame twice may result in corruption of this file.
"""
path = os.path.join(self.get_private_dir(create=True), "virtual_meta.yaml")
virtual_names = list(self.virtual_columns.keys()) + list(self.variables.keys())
units = {key: str(value) for key, value in self.units.items() | python | {
"resource": ""
} |
q267783 | DataFrame.write_meta | test | def write_meta(self):
"""Writes all meta data, ucd,description and units
The default implementation is to write this to a file called meta.yaml in the directory defined by
:func:`DataFrame.get_private_dir`. Other implementation may store this in the DataFrame file itself.
(For instance the vaex hdf5 implementation does this)
This method is called after virtual columns or variables are added. Upon opening a file, :func:`DataFrame.update_meta`
is called, so that the information is not lost between sessions.
Note: opening a DataFrame twice may result in corruption of this file.
"""
# raise NotImplementedError
| python | {
"resource": ""
} |
q267784 | DataFrame.subspaces | test | def subspaces(self, expressions_list=None, dimensions=None, exclude=None, **kwargs):
"""Generate a Subspaces object, based on a custom list of expressions or all possible combinations based on
dimension
:param expressions_list: list of list of expressions, where the inner list defines the subspace
:param dimensions: if given, generates a subspace with all possible combinations for that dimension
:param exclude: list of
"""
if dimensions is not None:
expressions_list = list(itertools.combinations(self.get_column_names(), dimensions))
if exclude is not None:
import six
def excluded(expressions):
if callable(exclude):
return exclude(expressions)
elif isinstance(exclude, six.string_types):
return exclude in expressions
elif isinstance(exclude, (list, tuple)):
# $#expressions = set(expressions)
for e in exclude:
if isinstance(e, six.string_types):
if e in expressions:
return True
elif isinstance(e, (list, tuple)):
if set(e).issubset(expressions):
| python | {
"resource": ""
} |
q267785 | DataFrame.set_variable | test | def set_variable(self, name, expression_or_value, write=True):
"""Set the variable to an expression or value defined by expression_or_value.
Example
>>> df.set_variable("a", 2.)
>>> df.set_variable("b", "a**2")
>>> df.get_variable("b")
'a**2'
>>> df.evaluate_variable("b")
| python | {
"resource": ""
} |
q267786 | DataFrame.evaluate_variable | test | def evaluate_variable(self, name):
"""Evaluates the variable given by name."""
if isinstance(self.variables[name], six.string_types):
# TODO: this does not | python | {
"resource": ""
} |
q267787 | DataFrame._evaluate_selection_mask | test | def _evaluate_selection_mask(self, name="default", i1=None, i2=None, selection=None, cache=False):
"""Internal use, ignores the filter"""
i1 = i1 or 0
i2 = i2 or len(self)
| python | {
"resource": ""
} |
q267788 | DataFrame.to_dict | test | def to_dict(self, column_names=None, selection=None, strings=True, virtual=False):
"""Return a dict containing the ndarray corresponding to the evaluated data
:param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used
:param selection: {selection}
:param strings: argument passed to DataFrame.get_column_names when column_names is None
| python | {
"resource": ""
} |
q267789 | DataFrame.to_copy | test | def to_copy(self, column_names=None, selection=None, strings=True, virtual=False, selections=True):
"""Return a copy of the DataFrame, if selection is None, it does not copy the data, it just has a reference
:param column_names: list of column names, to copy, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used
:param selection: {selection}
:param strings: argument passed to DataFrame.get_column_names when column_names is None
:param virtual: argument passed to DataFrame.get_column_names when column_names is None
:param selections: copy selections to a new DataFrame
| python | {
"resource": ""
} |
q267790 | DataFrame.to_pandas_df | test | def to_pandas_df(self, column_names=None, selection=None, strings=True, virtual=False, index_name=None):
"""Return a pandas DataFrame containing the ndarray corresponding to the evaluated data
If index is given, that column is used for the index of the dataframe.
Example
>>> df_pandas = df.to_pandas_df(["x", "y", "z"])
>>> df_copy = vaex.from_pandas(df_pandas)
:param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used
:param selection: {selection}
:param strings: argument passed to DataFrame.get_column_names when column_names is None
:param virtual: argument passed to DataFrame.get_column_names when column_names is None
:param index_column: if this column is given it is used for the index of the DataFrame
:return: pandas.DataFrame object
| python | {
"resource": ""
} |
q267791 | DataFrame.to_arrow_table | test | def to_arrow_table(self, column_names=None, selection=None, strings=True, virtual=False):
"""Returns an arrow Table object containing the arrays corresponding to the evaluated data
:param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used
:param selection: {selection}
:param strings: argument passed to DataFrame.get_column_names when column_names is None
| python | {
"resource": ""
} |
q267792 | DataFrame.to_astropy_table | test | def to_astropy_table(self, column_names=None, selection=None, strings=True, virtual=False, index=None):
"""Returns a astropy table object containing the ndarrays corresponding to the evaluated data
:param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used
:param selection: {selection}
:param strings: argument passed to DataFrame.get_column_names when column_names is None
:param virtual: argument passed to DataFrame.get_column_names when column_names is None
:param index: if this column is given it is used for the index of the DataFrame
:return: astropy.table.Table object
"""
from astropy.table import Table, Column, MaskedColumn
meta = dict()
meta["name"] = self.name
meta["description"] = | python | {
"resource": ""
} |
q267793 | DataFrame.add_column | test | def add_column(self, name, f_or_array):
"""Add an in memory array as a column."""
if isinstance(f_or_array, (np.ndarray, Column)):
data = ar = f_or_array
# it can be None when we have an 'empty' DataFrameArrays
if self._length_original is None:
self._length_unfiltered = _len(data)
self._length_original = _len(data)
self._index_end = self._length_unfiltered
if _len(ar) != self.length_original():
if self.filtered:
# give a better warning to avoid confusion
if len(self) == len(ar):
raise ValueError("Array is of length %s, while the length of the DataFrame is %s due to the filtering, the (unfiltered) length | python | {
"resource": ""
} |
q267794 | DataFrame.rename_column | test | def rename_column(self, name, new_name, unique=False, store_in_state=True):
"""Renames a column, not this is only the in memory name, this will not be reflected on disk"""
new_name = vaex.utils.find_valid_name(new_name, used=[] if not unique else list(self))
data = self.columns.get(name)
if data is not None:
del self.columns[name]
self.column_names[self.column_names.index(name)] = new_name
self.columns[new_name] = data
else:
expression = self.virtual_columns[name]
del self.virtual_columns[name]
| python | {
"resource": ""
} |
q267795 | DataFrame.add_virtual_columns_cartesian_to_polar | test | def add_virtual_columns_cartesian_to_polar(self, x="x", y="y", radius_out="r_polar", azimuth_out="phi_polar",
propagate_uncertainties=False,
radians=False):
"""Convert cartesian to polar coordinates
:param x: expression for x
:param y: expression for y
:param radius_out: name for the virtual column for the radius
:param azimuth_out: name for the virtual column for the azimuth angle
:param propagate_uncertainties: {propagate_uncertainties}
:param radians: if True, azimuth is in radians, defaults to degrees
:return:
"""
x = self[x]
| python | {
"resource": ""
} |
q267796 | DataFrame.add_virtual_columns_cartesian_velocities_to_spherical | test | def add_virtual_columns_cartesian_velocities_to_spherical(self, x="x", y="y", z="z", vx="vx", vy="vy", vz="vz", vr="vr", vlong="vlong", vlat="vlat", distance=None):
"""Concert velocities from a cartesian to a spherical coordinate system
TODO: errors
:param x: name of x column (input)
:param y: y
:param z: z
:param vx: vx
:param vy: vy
:param vz: vz
:param vr: name of the column for the radial velocity in the r direction (output)
:param vlong: name of the column for the velocity component in the longitude direction (output)
:param vlat: name of the column for the velocity component in the latitude direction, positive points to the north pole (output)
:param distance: Expression for distance, if not given defaults to sqrt(x**2+y**2+z**2), but if this column already exists, passing this expression may lead to a better performance
| python | {
"resource": ""
} |
q267797 | DataFrame.add_virtual_columns_cartesian_velocities_to_polar | test | def add_virtual_columns_cartesian_velocities_to_polar(self, x="x", y="y", vx="vx", radius_polar=None, vy="vy", vr_out="vr_polar", vazimuth_out="vphi_polar",
propagate_uncertainties=False,):
"""Convert cartesian to polar velocities.
:param x:
:param y:
:param vx:
:param radius_polar: Optional expression for the radius, may lead to a better performance when given.
:param vy:
:param vr_out:
:param vazimuth_out:
:param propagate_uncertainties: {propagate_uncertainties}
:return:
"""
x = self._expr(x) | python | {
"resource": ""
} |
q267798 | DataFrame.add_virtual_columns_polar_velocities_to_cartesian | test | def add_virtual_columns_polar_velocities_to_cartesian(self, x='x', y='y', azimuth=None, vr='vr_polar', vazimuth='vphi_polar', vx_out='vx', vy_out='vy', propagate_uncertainties=False):
""" Convert cylindrical polar velocities to Cartesian.
:param x:
:param y:
:param azimuth: Optional expression for the azimuth in degrees , may lead to a better performance when given.
:param vr:
:param vazimuth:
:param vx_out:
:param vy_out:
:param propagate_uncertainties: {propagate_uncertainties}
"""
x = self._expr(x)
y = self._expr(y)
vr = self._expr(vr)
vazimuth | python | {
"resource": ""
} |
q267799 | DataFrame.add_virtual_columns_rotation | test | def add_virtual_columns_rotation(self, x, y, xnew, ynew, angle_degrees, propagate_uncertainties=False):
"""Rotation in 2d.
:param str x: Name/expression of x column
:param str y: idem for y
:param str xnew: name of transformed x column
:param str ynew:
:param float angle_degrees: rotation in degrees, anti clockwise
:return:
"""
x = _ensure_string_from_expression(x)
y = _ensure_string_from_expression(y)
theta = np.radians(angle_degrees)
matrix = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
m = matrix_name = x + "_" + y + "_rot"
for i in range(2):
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.