_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q267800 | DataFrame.add_virtual_columns_spherical_to_cartesian | test | def add_virtual_columns_spherical_to_cartesian(self, alpha, delta, distance, xname="x", yname="y", zname="z",
propagate_uncertainties=False,
center=[0, 0, 0], center_name="solar_position", radians=False):
"""Convert spherical to cartesian coordinates.
:param alpha:
:param delta: polar angle, ranging from the -90 (south pole) to 90 (north pole)
:param distance: radial distance, determines the units of x, y and z
:param xname:
:param yname:
:param zname:
:param propagate_uncertainties: {propagate_uncertainties}
:param center:
:param center_name:
:param radians:
:return:
"""
alpha = self._expr(alpha)
delta = self._expr(delta)
distance = self._expr(distance)
if not radians:
alpha = alpha * self._expr('pi')/180
delta = delta * self._expr('pi')/180
# TODO: use sth like .optimize by default to get rid of the +0 ?
if center[0]:
self[xname] = np.cos(alpha) * np.cos(delta) * distance + center[0]
else:
self[xname] = np.cos(alpha) * np.cos(delta) * distance
if center[1]:
self[yname] = np.sin(alpha) * np.cos(delta) * distance + center[1]
else:
self[yname] = np.sin(alpha) * np.cos(delta) * distance
if center[2]:
self[zname] = np.sin(delta) * distance + center[2]
else:
self[zname] = np.sin(delta) * distance
if propagate_uncertainties:
self.propagate_uncertainties([self[xname], self[yname], self[zname]]) | python | {
"resource": ""
} |
q267801 | DataFrame.add_virtual_columns_cartesian_to_spherical | test | def add_virtual_columns_cartesian_to_spherical(self, x="x", y="y", z="z", alpha="l", delta="b", distance="distance", radians=False, center=None, center_name="solar_position"):
"""Convert cartesian to spherical coordinates.
:param x:
:param y:
:param z:
:param alpha:
:param delta: name for polar angle, ranges from -90 to 90 (or -pi to pi when radians is True).
:param distance:
:param radians:
:param center:
:param center_name:
:return:
"""
transform = "" if radians else "*180./pi"
if center is not None:
self.add_variable(center_name, center)
if center is not None and center[0] != 0:
x = "({x} - {center_name}[0])".format(**locals())
if center is not None and center[1] != 0:
y = "({y} - {center_name}[1])".format(**locals())
if center is not None and center[2] != 0:
z = "({z} - {center_name}[2])".format(**locals())
self.add_virtual_column(distance, "sqrt({x}**2 + {y}**2 + {z}**2)".format(**locals()))
# self.add_virtual_column(alpha, "((arctan2({y}, {x}) + 2*pi) % (2*pi)){transform}".format(**locals()))
self.add_virtual_column(alpha, "arctan2({y}, {x}){transform}".format(**locals()))
self.add_virtual_column(delta, "(-arccos({z}/{distance})+pi/2){transform}".format(**locals())) | python | {
"resource": ""
} |
q267802 | DataFrame.add_virtual_column | test | def add_virtual_column(self, name, expression, unique=False):
"""Add a virtual column to the DataFrame.
Example:
>>> df.add_virtual_column("r", "sqrt(x**2 + y**2 + z**2)")
>>> df.select("r < 10")
:param: str name: name of virtual column
:param: expression: expression for the column
:param str unique: if name is already used, make it unique by adding a postfix, e.g. _1, or _2
"""
type = "change" if name in self.virtual_columns else "add"
expression = _ensure_string_from_expression(expression)
if name in self.get_column_names(virtual=False):
renamed = '__' +vaex.utils.find_valid_name(name, used=self.get_column_names())
expression = self._rename(name, renamed, expression)[0].expression
name = vaex.utils.find_valid_name(name, used=[] if not unique else self.get_column_names())
self.virtual_columns[name] = expression
self.column_names.append(name)
self._save_assign_expression(name)
self.signal_column_changed.emit(self, name, "add") | python | {
"resource": ""
} |
q267803 | DataFrame.delete_virtual_column | test | def delete_virtual_column(self, name):
"""Deletes a virtual column from a DataFrame."""
del self.virtual_columns[name]
self.signal_column_changed.emit(self, name, "delete") | python | {
"resource": ""
} |
q267804 | DataFrame.add_variable | test | def add_variable(self, name, expression, overwrite=True, unique=True):
"""Add a variable to to a DataFrame.
A variable may refer to other variables, and virtual columns and expression may refer to variables.
Example
>>> df.add_variable('center', 0)
>>> df.add_virtual_column('x_prime', 'x-center')
>>> df.select('x_prime < 0')
:param: str name: name of virtual varible
:param: expression: expression for the variable
"""
if unique or overwrite or name not in self.variables:
existing_names = self.get_column_names(virtual=False) + list(self.variables.keys())
name = vaex.utils.find_valid_name(name, used=[] if not unique else existing_names)
self.variables[name] = expression
self.signal_variable_changed.emit(self, name, "add")
if unique:
return name | python | {
"resource": ""
} |
q267805 | DataFrame.delete_variable | test | def delete_variable(self, name):
"""Deletes a variable from a DataFrame."""
del self.variables[name]
self.signal_variable_changed.emit(self, name, "delete") | python | {
"resource": ""
} |
q267806 | DataFrame.tail | test | def tail(self, n=10):
"""Return a shallow copy a DataFrame with the last n rows."""
N = len(self)
# self.cat(i1=max(0, N-n), i2=min(len(self), N))
return self[max(0, N - n):min(len(self), N)] | python | {
"resource": ""
} |
q267807 | DataFrame.head_and_tail_print | test | def head_and_tail_print(self, n=5):
"""Display the first and last n elements of a DataFrame."""
from IPython import display
display.display(display.HTML(self._head_and_tail_table(n))) | python | {
"resource": ""
} |
q267808 | DataFrame.describe | test | def describe(self, strings=True, virtual=True, selection=None):
"""Give a description of the DataFrame.
>>> import vaex
>>> df = vaex.example()[['x', 'y', 'z']]
>>> df.describe()
x y z
dtype float64 float64 float64
count 330000 330000 330000
missing 0 0 0
mean -0.0671315 -0.0535899 0.0169582
std 7.31746 7.78605 5.05521
min -128.294 -71.5524 -44.3342
max 271.366 146.466 50.7185
>>> df.describe(selection=df.x > 0)
x y z
dtype float64 float64 float64
count 164060 164060 164060
missing 165940 165940 165940
mean 5.13572 -0.486786 -0.0868073
std 5.18701 7.61621 5.02831
min 1.51635e-05 -71.5524 -44.3342
max 271.366 78.0724 40.2191
:param bool strings: Describe string columns or not
:param bool virtual: Describe virtual columns or not
:param selection: Optional selection to use.
:return: Pandas dataframe
"""
import pandas as pd
N = len(self)
columns = {}
for feature in self.get_column_names(strings=strings, virtual=virtual)[:]:
dtype = str(self.dtype(feature)) if self.dtype(feature) != str else 'str'
if self.dtype(feature) == str_type or self.dtype(feature).kind in ['S', 'U', 'O']:
count = self.count(feature, selection=selection, delay=True)
self.execute()
count = count.get()
columns[feature] = ((dtype, count, N-count, '--', '--', '--', '--'))
else:
count = self.count(feature, selection=selection, delay=True)
mean = self.mean(feature, selection=selection, delay=True)
std = self.std(feature, selection=selection, delay=True)
minmax = self.minmax(feature, selection=selection, delay=True)
self.execute()
count, mean, std, minmax = count.get(), mean.get(), std.get(), minmax.get()
count = int(count)
columns[feature] = ((dtype, count, N-count, mean, std, minmax[0], minmax[1]))
return pd.DataFrame(data=columns, index=['dtype', 'count', 'missing', 'mean', 'std', 'min', 'max']) | python | {
"resource": ""
} |
q267809 | DataFrame.cat | test | def cat(self, i1, i2, format='html'):
"""Display the DataFrame from row i1 till i2
For format, see https://pypi.org/project/tabulate/
:param int i1: Start row
:param int i2: End row.
:param str format: Format to use, e.g. 'html', 'plain', 'latex'
"""
from IPython import display
if format == 'html':
output = self._as_html_table(i1, i2)
display.display(display.HTML(output))
else:
output = self._as_table(i1, i2, format=format)
print(output) | python | {
"resource": ""
} |
q267810 | DataFrame.set_current_row | test | def set_current_row(self, value):
"""Set the current row, and emit the signal signal_pick."""
if (value is not None) and ((value < 0) or (value >= len(self))):
raise IndexError("index %d out of range [0,%d]" % (value, len(self)))
self._current_row = value
self.signal_pick.emit(self, value) | python | {
"resource": ""
} |
q267811 | DataFrame.get_column_names | test | def get_column_names(self, virtual=True, strings=True, hidden=False, regex=None):
"""Return a list of column names
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, x2=2, y=3, s='string')
>>> df['r'] = (df.x**2 + df.y**2)**2
>>> df.get_column_names()
['x', 'x2', 'y', 's', 'r']
>>> df.get_column_names(virtual=False)
['x', 'x2', 'y', 's']
>>> df.get_column_names(regex='x.*')
['x', 'x2']
:param virtual: If False, skip virtual columns
:param hidden: If False, skip hidden columns
:param strings: If False, skip string columns
:param regex: Only return column names matching the (optional) regular expression
:rtype: list of str
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, x2=2, y=3, s='string')
>>> df['r'] = (df.x**2 + df.y**2)**2
>>> df.get_column_names()
['x', 'x2', 'y', 's', 'r']
>>> df.get_column_names(virtual=False)
['x', 'x2', 'y', 's']
>>> df.get_column_names(regex='x.*')
['x', 'x2']
"""
def column_filter(name):
'''Return True if column with specified name should be returned'''
if regex and not re.match(regex, name):
return False
if not virtual and name in self.virtual_columns:
return False
if not strings and (self.dtype(name) == str_type or self.dtype(name).type == np.string_):
return False
if not hidden and name.startswith('__'):
return False
return True
return [name for name in self.column_names if column_filter(name)] | python | {
"resource": ""
} |
q267812 | DataFrame.trim | test | def trim(self, inplace=False):
'''Return a DataFrame, where all columns are 'trimmed' by the active range.
For the returned DataFrame, df.get_active_range() returns (0, df.length_original()).
{note_copy}
:param inplace: {inplace}
:rtype: DataFrame
'''
df = self if inplace else self.copy()
for name in df:
column = df.columns.get(name)
if column is not None:
if self._index_start == 0 and len(column) == self._index_end:
pass # we already assigned it in .copy
else:
if isinstance(column, np.ndarray): # real array
df.columns[name] = column[self._index_start:self._index_end]
else:
df.columns[name] = column.trim(self._index_start, self._index_end)
df._length_original = self.length_unfiltered()
df._length_unfiltered = df._length_original
df._index_start = 0
df._index_end = df._length_original
df._active_fraction = 1
return df | python | {
"resource": ""
} |
q267813 | DataFrame.take | test | def take(self, indices):
'''Returns a DataFrame containing only rows indexed by indices
{note_copy}
Example:
>>> import vaex, numpy as np
>>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd']), x=np.arange(1,5))
>>> df.take([0,2])
# s x
0 a 1
1 c 3
:param indices: sequence (list or numpy array) with row numbers
:return: DataFrame which is a shallow copy of the original data.
:rtype: DataFrame
'''
df = self.copy()
# if the columns in ds already have a ColumnIndex
# we could do, direct_indices = df.column['bla'].indices[indices]
# which should be shared among multiple ColumnIndex'es, so we store
# them in this dict
direct_indices_map = {}
indices = np.array(indices)
for name in df:
column = df.columns.get(name)
if column is not None:
# we optimize this somewhere, so we don't do multiple
# levels of indirection
if isinstance(column, ColumnIndexed):
# TODO: think about what happpens when the indices are masked.. ?
if id(column.indices) not in direct_indices_map:
direct_indices = column.indices[indices]
direct_indices_map[id(column.indices)] = direct_indices
else:
direct_indices = direct_indices_map[id(column.indices)]
df.columns[name] = ColumnIndexed(column.df, direct_indices, column.name)
else:
df.columns[name] = ColumnIndexed(self, indices, name)
df._length_original = len(indices)
df._length_unfiltered = df._length_original
df.set_selection(None, name=FILTER_SELECTION_NAME)
return df | python | {
"resource": ""
} |
q267814 | DataFrame.extract | test | def extract(self):
'''Return a DataFrame containing only the filtered rows.
{note_copy}
The resulting DataFrame may be more efficient to work with when the original DataFrame is
heavily filtered (contains just a small number of rows).
If no filtering is applied, it returns a trimmed view.
For the returned df, len(df) == df.length_original() == df.length_unfiltered()
:rtype: DataFrame
'''
trimmed = self.trim()
if trimmed.filtered:
indices = trimmed._filtered_range_to_unfiltered_indices(0, len(trimmed))
return trimmed.take(indices)
else:
return trimmed | python | {
"resource": ""
} |
q267815 | DataFrame.sample | test | def sample(self, n=None, frac=None, replace=False, weights=None, random_state=None):
'''Returns a DataFrame with a random set of rows
{note_copy}
Provide either n or frac.
Example:
>>> import vaex, numpy as np
>>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd']), x=np.arange(1,5))
>>> df
# s x
0 a 1
1 b 2
2 c 3
3 d 4
>>> df.sample(n=2, random_state=42) # 2 random rows, fixed seed
# s x
0 b 2
1 d 4
>>> df.sample(frac=1, random_state=42) # 'shuffling'
# s x
0 c 3
1 a 1
2 d 4
3 b 2
>>> df.sample(frac=1, replace=True, random_state=42) # useful for bootstrap (may contain repeated samples)
# s x
0 d 4
1 a 1
2 a 1
3 d 4
:param int n: number of samples to take (default 1 if frac is None)
:param float frac: fractional number of takes to take
:param bool replace: If true, a row may be drawn multiple times
:param str or expression weights: (unnormalized) probability that a row can be drawn
:param int or RandomState: seed or RandomState for reproducability, when None a random seed it chosen
:return: {return_shallow_copy}
:rtype: DataFrame
'''
self = self.extract()
if type(random_state) == int or random_state is None:
random_state = np.random.RandomState(seed=random_state)
if n is None and frac is None:
n = 1
elif frac is not None:
n = int(round(frac * len(self)))
weights_values = None
if weights is not None:
weights_values = self.evaluate(weights)
weights_values = weights_values / self.sum(weights)
indices = random_state.choice(len(self), n, replace=replace, p=weights_values)
return self.take(indices) | python | {
"resource": ""
} |
q267816 | DataFrame.split_random | test | def split_random(self, frac, random_state=None):
'''Returns a list containing random portions of the DataFrame.
{note_copy}
Example:
>>> import vaex, import numpy as np
>>> np.random.seed(111)
>>> df = vaex.from_arrays(x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> for dfs in df.split_random(frac=0.3, random_state=42):
... print(dfs.x.values)
...
[8 1 5]
[0 7 2 9 4 3 6]
>>> for split in df.split_random(frac=[0.2, 0.3, 0.5], random_state=42):
... print(dfs.x.values)
[8 1]
[5 0 7]
[2 9 4 3 6]
:param int/list frac: If int will split the DataFrame in two portions, the first of which will have size as specified by this parameter. If list, the generator will generate as many portions as elements in the list, where each element defines the relative fraction of that portion.
:param int random_state: (default, None) Random number seed for reproducibility.
:return: A list of DataFrames.
:rtype: list
'''
self = self.extract()
if type(random_state) == int or random_state is None:
random_state = np.random.RandomState(seed=random_state)
indices = random_state.choice(len(self), len(self), replace=False)
return self.take(indices).split(frac) | python | {
"resource": ""
} |
q267817 | DataFrame.split | test | def split(self, frac):
'''Returns a list containing ordered subsets of the DataFrame.
{note_copy}
Example:
>>> import vaex
>>> df = vaex.from_arrays(x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> for dfs in df.split(frac=0.3):
... print(dfs.x.values)
...
[0 1 3]
[3 4 5 6 7 8 9]
>>> for split in df.split(frac=[0.2, 0.3, 0.5]):
... print(dfs.x.values)
[0 1]
[2 3 4]
[5 6 7 8 9]
:param int/list frac: If int will split the DataFrame in two portions, the first of which will have size as specified by this parameter. If list, the generator will generate as many portions as elements in the list, where each element defines the relative fraction of that portion.
:return: A list of DataFrames.
:rtype: list
'''
self = self.extract()
if _issequence(frac):
# make sure it is normalized
total = sum(frac)
frac = [k / total for k in frac]
else:
assert frac <= 1, "fraction should be <= 1"
frac = [frac, 1 - frac]
offsets = np.round(np.cumsum(frac) * len(self)).astype(np.int64)
start = 0
for offset in offsets:
yield self[start:offset]
start = offset | python | {
"resource": ""
} |
q267818 | DataFrame.sort | test | def sort(self, by, ascending=True, kind='quicksort'):
'''Return a sorted DataFrame, sorted by the expression 'by'
{note_copy}
{note_filter}
Example:
>>> import vaex, numpy as np
>>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd']), x=np.arange(1,5))
>>> df['y'] = (df.x-1.8)**2
>>> df
# s x y
0 a 1 0.64
1 b 2 0.04
2 c 3 1.44
3 d 4 4.84
>>> df.sort('y', ascending=False) # Note: passing '(x-1.8)**2' gives the same result
# s x y
0 d 4 4.84
1 c 3 1.44
2 a 1 0.64
3 b 2 0.04
:param str or expression by: expression to sort by
:param bool ascending: ascending (default, True) or descending (False)
:param str kind: kind of algorithm to use (passed to numpy.argsort)
'''
self = self.trim()
values = self.evaluate(by, filtered=False)
indices = np.argsort(values, kind=kind)
if not ascending:
indices = indices[::-1].copy() # this may be used a lot, so copy for performance
return self.take(indices) | python | {
"resource": ""
} |
q267819 | DataFrame.materialize | test | def materialize(self, virtual_column, inplace=False):
'''Returns a new DataFrame where the virtual column is turned into an in memory numpy array.
Example:
>>> x = np.arange(1,4)
>>> y = np.arange(2,5)
>>> df = vaex.from_arrays(x=x, y=y)
>>> df['r'] = (df.x**2 + df.y**2)**0.5 # 'r' is a virtual column (computed on the fly)
>>> df = df.materialize('r') # now 'r' is a 'real' column (i.e. a numpy array)
:param inplace: {inplace}
'''
df = self.trim(inplace=inplace)
virtual_column = _ensure_string_from_expression(virtual_column)
if virtual_column not in df.virtual_columns:
raise KeyError('Virtual column not found: %r' % virtual_column)
ar = df.evaluate(virtual_column, filtered=False)
del df[virtual_column]
df.add_column(virtual_column, ar)
return df | python | {
"resource": ""
} |
q267820 | DataFrame.selection_undo | test | def selection_undo(self, name="default", executor=None):
"""Undo selection, for the name."""
logger.debug("undo")
executor = executor or self.executor
assert self.selection_can_undo(name=name)
selection_history = self.selection_histories[name]
index = self.selection_history_indices[name]
self.selection_history_indices[name] -= 1
self.signal_selection_changed.emit(self)
logger.debug("undo: selection history is %r, index is %r", selection_history, self.selection_history_indices[name]) | python | {
"resource": ""
} |
q267821 | DataFrame.selection_redo | test | def selection_redo(self, name="default", executor=None):
"""Redo selection, for the name."""
logger.debug("redo")
executor = executor or self.executor
assert self.selection_can_redo(name=name)
selection_history = self.selection_histories[name]
index = self.selection_history_indices[name]
next = selection_history[index + 1]
self.selection_history_indices[name] += 1
self.signal_selection_changed.emit(self)
logger.debug("redo: selection history is %r, index is %r", selection_history, index) | python | {
"resource": ""
} |
q267822 | DataFrame.selection_can_redo | test | def selection_can_redo(self, name="default"):
"""Can selection name be redone?"""
return (self.selection_history_indices[name] + 1) < len(self.selection_histories[name]) | python | {
"resource": ""
} |
q267823 | DataFrame.select | test | def select(self, boolean_expression, mode="replace", name="default", executor=None):
"""Perform a selection, defined by the boolean expression, and combined with the previous selection using the given mode.
Selections are recorded in a history tree, per name, undo/redo can be done for them separately.
:param str boolean_expression: Any valid column expression, with comparison operators
:param str mode: Possible boolean operator: replace/and/or/xor/subtract
:param str name: history tree or selection 'slot' to use
:param executor:
:return:
"""
boolean_expression = _ensure_string_from_expression(boolean_expression)
if boolean_expression is None and not self.has_selection(name=name):
pass # we don't want to pollute the history with many None selections
self.signal_selection_changed.emit(self) # TODO: unittest want to know, does this make sense?
else:
def create(current):
return selections.SelectionExpression(boolean_expression, current, mode) if boolean_expression else None
self._selection(create, name) | python | {
"resource": ""
} |
q267824 | DataFrame.select_non_missing | test | def select_non_missing(self, drop_nan=True, drop_masked=True, column_names=None, mode="replace", name="default"):
"""Create a selection that selects rows having non missing values for all columns in column_names.
The name reflect Panda's, no rows are really dropped, but a mask is kept to keep track of the selection
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when there is a masked value in any of the columns
:param column_names: The columns to consider, default: all (real, non-virtual) columns
:param str mode: Possible boolean operator: replace/and/or/xor/subtract
:param str name: history tree or selection 'slot' to use
:return:
"""
column_names = column_names or self.get_column_names(virtual=False)
def create(current):
return selections.SelectionDropNa(drop_nan, drop_masked, column_names, current, mode)
self._selection(create, name) | python | {
"resource": ""
} |
q267825 | DataFrame.dropna | test | def dropna(self, drop_nan=True, drop_masked=True, column_names=None):
"""Create a shallow copy of a DataFrame, with filtering set using select_non_missing.
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when there is a masked value in any of the columns
:param column_names: The columns to consider, default: all (real, non-virtual) columns
:rtype: DataFrame
"""
copy = self.copy()
copy.select_non_missing(drop_nan=drop_nan, drop_masked=drop_masked, column_names=column_names,
name=FILTER_SELECTION_NAME, mode='and')
return copy | python | {
"resource": ""
} |
q267826 | DataFrame.select_rectangle | test | def select_rectangle(self, x, y, limits, mode="replace", name="default"):
"""Select a 2d rectangular box in the space given by x and y, bounds by limits.
Example:
>>> df.select_box('x', 'y', [(0, 10), (0, 1)])
:param x: expression for the x space
:param y: expression fo the y space
:param limits: sequence of shape [(x1, x2), (y1, y2)]
:param mode:
"""
self.select_box([x, y], limits, mode=mode, name=name) | python | {
"resource": ""
} |
q267827 | DataFrame.select_box | test | def select_box(self, spaces, limits, mode="replace", name="default"):
"""Select a n-dimensional rectangular box bounded by limits.
The following examples are equivalent:
>>> df.select_box(['x', 'y'], [(0, 10), (0, 1)])
>>> df.select_rectangle('x', 'y', [(0, 10), (0, 1)])
:param spaces: list of expressions
:param limits: sequence of shape [(x1, x2), (y1, y2)]
:param mode:
:param name:
:return:
"""
sorted_limits = [(min(l), max(l)) for l in limits]
expressions = ["((%s) >= %f) & ((%s) <= %f)" % (expression, lmin, expression, lmax) for
(expression, (lmin, lmax)) in zip(spaces, sorted_limits)]
self.select("&".join(expressions), mode=mode, name=name) | python | {
"resource": ""
} |
q267828 | DataFrame.select_circle | test | def select_circle(self, x, y, xc, yc, r, mode="replace", name="default", inclusive=True):
"""
Select a circular region centred on xc, yc, with a radius of r.
Example:
>>> df.select_circle('x','y',2,3,1)
:param x: expression for the x space
:param y: expression for the y space
:param xc: location of the centre of the circle in x
:param yc: location of the centre of the circle in y
:param r: the radius of the circle
:param name: name of the selection
:param mode:
:return:
"""
# expr = "({x}-{xc})**2 + ({y}-{yc})**2 <={r}**2".format(**locals())
if inclusive:
expr = (self[x] - xc)**2 + (self[y] - yc)**2 <= r**2
else:
expr = (self[x] - xc)**2 + (self[y] - yc)**2 < r**2
self.select(boolean_expression=expr, mode=mode, name=name) | python | {
"resource": ""
} |
q267829 | DataFrame.select_ellipse | test | def select_ellipse(self, x, y, xc, yc, width, height, angle=0, mode="replace", name="default", radians=False, inclusive=True):
"""
Select an elliptical region centred on xc, yc, with a certain width, height
and angle.
Example:
>>> df.select_ellipse('x','y', 2, -1, 5,1, 30, name='my_ellipse')
:param x: expression for the x space
:param y: expression for the y space
:param xc: location of the centre of the ellipse in x
:param yc: location of the centre of the ellipse in y
:param width: the width of the ellipse (diameter)
:param height: the width of the ellipse (diameter)
:param angle: (degrees) orientation of the ellipse, counter-clockwise
measured from the y axis
:param name: name of the selection
:param mode:
:return:
"""
# Computing the properties of the ellipse prior to selection
if radians:
pass
else:
alpha = np.deg2rad(angle)
xr = width / 2
yr = height / 2
r = max(xr, yr)
a = xr / r
b = yr / r
expr = "(({x}-{xc})*cos({alpha})+({y}-{yc})*sin({alpha}))**2/{a}**2 + (({x}-{xc})*sin({alpha})-({y}-{yc})*cos({alpha}))**2/{b}**2 <= {r}**2".format(**locals())
if inclusive:
expr = ((self[x] - xc) * np.cos(alpha) + (self[y] - yc) * np.sin(alpha))**2 / a**2 + ((self[x] - xc) * np.sin(alpha) - (self[y] - yc) * np.cos(alpha))**2 / b**2 <= r**2
else:
expr = ((self[x] - xc) * np.cos(alpha) + (self[y] - yc) * np.sin(alpha))**2 / a**2 + ((self[x] - xc) * np.sin(alpha) - (self[y] - yc) * np.cos(alpha))**2 / b**2 < r**2
self.select(boolean_expression=expr, mode=mode, name=name) | python | {
"resource": ""
} |
q267830 | DataFrame.select_lasso | test | def select_lasso(self, expression_x, expression_y, xsequence, ysequence, mode="replace", name="default", executor=None):
"""For performance reasons, a lasso selection is handled differently.
:param str expression_x: Name/expression for the x coordinate
:param str expression_y: Name/expression for the y coordinate
:param xsequence: list of x numbers defining the lasso, together with y
:param ysequence:
:param str mode: Possible boolean operator: replace/and/or/xor/subtract
:param str name:
:param executor:
:return:
"""
def create(current):
return selections.SelectionLasso(expression_x, expression_y, xsequence, ysequence, current, mode)
self._selection(create, name, executor=executor) | python | {
"resource": ""
} |
q267831 | DataFrame.select_inverse | test | def select_inverse(self, name="default", executor=None):
"""Invert the selection, i.e. what is selected will not be, and vice versa
:param str name:
:param executor:
:return:
"""
def create(current):
return selections.SelectionInvert(current)
self._selection(create, name, executor=executor) | python | {
"resource": ""
} |
q267832 | DataFrame.set_selection | test | def set_selection(self, selection, name="default", executor=None):
"""Sets the selection object
:param selection: Selection object
:param name: selection 'slot'
:param executor:
:return:
"""
def create(current):
return selection
self._selection(create, name, executor=executor, execute_fully=True) | python | {
"resource": ""
} |
q267833 | DataFrame._selection | test | def _selection(self, create_selection, name, executor=None, execute_fully=False):
"""select_lasso and select almost share the same code"""
selection_history = self.selection_histories[name]
previous_index = self.selection_history_indices[name]
current = selection_history[previous_index] if selection_history else None
selection = create_selection(current)
executor = executor or self.executor
selection_history.append(selection)
self.selection_history_indices[name] += 1
# clip any redo history
del selection_history[self.selection_history_indices[name]:-1]
if 0:
if self.is_local():
if selection:
# result = selection.execute(executor=executor, execute_fully=execute_fully)
result = vaex.promise.Promise.fulfilled(None)
self.signal_selection_changed.emit(self)
else:
result = vaex.promise.Promise.fulfilled(None)
self.signal_selection_changed.emit(self)
else:
self.signal_selection_changed.emit(self)
result = vaex.promise.Promise.fulfilled(None)
self.signal_selection_changed.emit(self)
result = vaex.promise.Promise.fulfilled(None)
logger.debug("select selection history is %r, index is %r", selection_history, self.selection_history_indices[name])
return result | python | {
"resource": ""
} |
q267834 | DataFrame._find_valid_name | test | def _find_valid_name(self, initial_name):
'''Finds a non-colliding name by optional postfixing'''
return vaex.utils.find_valid_name(initial_name, used=self.get_column_names(hidden=True)) | python | {
"resource": ""
} |
q267835 | DataFrame._root_nodes | test | def _root_nodes(self):
"""Returns a list of string which are the virtual columns that are not used in any other virtual column."""
# these lists (~used as ordered set) keep track of leafes and root nodes
# root nodes
root_nodes = []
leafes = []
def walk(node):
# this function recursively walks the expression graph
if isinstance(node, six.string_types):
# we end up at a leaf
leafes.append(node)
if node in root_nodes: # so it cannot be a root node
root_nodes.remove(node)
else:
node_repr, fname, fobj, deps = node
if node_repr in self.virtual_columns:
# we encountered a virtual column, similar behaviour as leaf
leafes.append(node_repr)
if node_repr in root_nodes:
root_nodes.remove(node_repr)
# resursive part
for dep in deps:
walk(dep)
for column in self.virtual_columns.keys():
if column not in leafes:
root_nodes.append(column)
node = self[column]._graph()
# we don't do the virtual column itself, just it's depedencies
node_repr, fname, fobj, deps = node
for dep in deps:
walk(dep)
return root_nodes | python | {
"resource": ""
} |
q267836 | DataFrame._graphviz | test | def _graphviz(self, dot=None):
"""Return a graphviz.Digraph object with a graph of all virtual columns"""
from graphviz import Digraph
dot = dot or Digraph(comment='whole dataframe')
root_nodes = self._root_nodes()
for column in root_nodes:
self[column]._graphviz(dot=dot)
return dot | python | {
"resource": ""
} |
q267837 | DataFrameLocal.categorize | test | def categorize(self, column, labels=None, check=True):
"""Mark column as categorical, with given labels, assuming zero indexing"""
column = _ensure_string_from_expression(column)
if check:
vmin, vmax = self.minmax(column)
if labels is None:
N = int(vmax + 1)
labels = list(map(str, range(N)))
if (vmax - vmin) >= len(labels):
raise ValueError('value of {} found, which is larger than number of labels {}'.format(vmax, len(labels)))
self._categories[column] = dict(labels=labels, N=len(labels)) | python | {
"resource": ""
} |
q267838 | DataFrameLocal.ordinal_encode | test | def ordinal_encode(self, column, values=None, inplace=False):
"""Encode column as ordinal values and mark it as categorical.
The existing column is renamed to a hidden column and replaced by a numerical columns
with values between [0, len(values)-1].
"""
column = _ensure_string_from_expression(column)
df = self if inplace else self.copy()
# for the codes, we need to work on the unfiltered dataset, since the filter
# may change, and we also cannot add an array that is smaller in length
df_unfiltered = df.copy()
# maybe we need some filter manipulation methods
df_unfiltered.select_nothing(name=FILTER_SELECTION_NAME)
df_unfiltered._length_unfiltered = df._length_original
df_unfiltered.set_active_range(0, df._length_original)
# codes point to the index of found_values
# meaning: found_values[codes[0]] == ds[column].values[0]
found_values, codes = df_unfiltered.unique(column, return_inverse=True)
if values is None:
values = found_values
else:
# we have specified which values we should support, anything
# not found will be masked
translation = np.zeros(len(found_values), dtype=np.uint64)
# mark values that are in the column, but not in values with a special value
missing_value = len(found_values)
for i, found_value in enumerate(found_values):
try:
found_value = found_value.decode('ascii')
except:
pass
if found_value not in values: # not present, we need a missing value
translation[i] = missing_value
else:
translation[i] = values.index(found_value)
codes = translation[codes]
if missing_value in translation:
# all special values will be marked as missing
codes = np.ma.masked_array(codes, codes==missing_value)
original_column = df.rename_column(column, '__original_' + column, unique=True)
labels = [str(k) for k in values]
df.add_column(column, codes)
df._categories[column] = dict(labels=labels, N=len(values), values=values)
return df | python | {
"resource": ""
} |
q267839 | DataFrameLocal.data | test | def data(self):
"""Gives direct access to the data as numpy arrays.
Convenient when working with IPython in combination with small DataFrames, since this gives tab-completion.
Only real columns (i.e. no virtual) columns can be accessed, for getting the data from virtual columns, use
DataFrame.evalulate(...).
Columns can be accesed by there names, which are attributes. The attribues are of type numpy.ndarray.
Example:
>>> df = vaex.example()
>>> r = np.sqrt(df.data.x**2 + df.data.y**2)
"""
class Datas(object):
pass
datas = Datas()
for name, array in self.columns.items():
setattr(datas, name, array)
return datas | python | {
"resource": ""
} |
q267840 | DataFrameLocal.length | test | def length(self, selection=False):
"""Get the length of the DataFrames, for the selection of the whole DataFrame.
If selection is False, it returns len(df).
TODO: Implement this in DataFrameRemote, and move the method up in :func:`DataFrame.length`
:param selection: When True, will return the number of selected rows
:return:
"""
if selection:
return 0 if self.mask is None else np.sum(self.mask)
else:
return len(self) | python | {
"resource": ""
} |
q267841 | DataFrameLocal._hstack | test | def _hstack(self, other, prefix=None):
"""Join the columns of the other DataFrame to this one, assuming the ordering is the same"""
assert len(self) == len(other), "does not make sense to horizontally stack DataFrames with different lengths"
for name in other.get_column_names():
if prefix:
new_name = prefix + name
else:
new_name = name
self.add_column(new_name, other.columns[name]) | python | {
"resource": ""
} |
q267842 | DataFrameLocal.concat | test | def concat(self, other):
"""Concatenates two DataFrames, adding the rows of one the other DataFrame to the current, returned in a new DataFrame.
No copy of the data is made.
:param other: The other DataFrame that is concatenated with this DataFrame
:return: New DataFrame with the rows concatenated
:rtype: DataFrameConcatenated
"""
dfs = []
if isinstance(self, DataFrameConcatenated):
dfs.extend(self.dfs)
else:
dfs.extend([self])
if isinstance(other, DataFrameConcatenated):
dfs.extend(other.dfs)
else:
dfs.extend([other])
return DataFrameConcatenated(dfs) | python | {
"resource": ""
} |
q267843 | DataFrameLocal.export_hdf5 | test | def export_hdf5(self, path, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=False, sort=None, ascending=True):
"""Exports the DataFrame to a vaex hdf5 file
:param DataFrameLocal df: DataFrame to export
:param str path: path for file
:param lis[str] column_names: list of column names to export or None for all columns
:param str byteorder: = for native, < for little endian and > for big endian
:param bool shuffle: export rows in random order
:param bool selection: export selection or not
:param progress: progress callback that gets a progress fraction as argument and should return True to continue,
or a default progress bar when progress=True
:param: bool virtual: When True, export virtual columns
:param str sort: expression used for sorting the output
:param bool ascending: sort ascending (True) or descending
:return:
"""
import vaex.export
vaex.export.export_hdf5(self, path, column_names, byteorder, shuffle, selection, progress=progress, virtual=virtual, sort=sort, ascending=ascending) | python | {
"resource": ""
} |
q267844 | DataFrameArrays.add_column | test | def add_column(self, name, data):
"""Add a column to the DataFrame
:param str name: name of column
:param data: numpy array with the data
"""
# assert _is_array_type_ok(data), "dtype not supported: %r, %r" % (data.dtype, data.dtype.type)
# self._length = len(data)
# if self._length_unfiltered is None:
# self._length_unfiltered = len(data)
# self._length_original = len(data)
# self._index_end = self._length_unfiltered
super(DataFrameArrays, self).add_column(name, data)
self._length_unfiltered = int(round(self._length_original * self._active_fraction)) | python | {
"resource": ""
} |
q267845 | patch | test | def patch(f):
'''Adds method f to the DataFrame class'''
name = f.__name__
setattr(DataFrame, name, f)
return f | python | {
"resource": ""
} |
q267846 | register_function | test | def register_function(scope=None, as_property=False, name=None):
"""Decorator to register a new function with vaex.
Example:
>>> import vaex
>>> df = vaex.example()
>>> @vaex.register_function()
>>> def invert(x):
>>> return 1/x
>>> df.x.invert()
>>> import numpy as np
>>> df = vaex.from_arrays(departure=np.arange('2015-01-01', '2015-12-05', dtype='datetime64'))
>>> @vaex.register_function(as_property=True, scope='dt')
>>> def dt_relative_day(x):
>>> return vaex.functions.dt_dayofyear(x)/365.
>>> df.departure.dt.relative_day
"""
prefix = ''
if scope:
prefix = scope + "_"
if scope not in scopes:
raise KeyError("unknown scope")
def wrapper(f, name=name):
name = name or f.__name__
# remove possible prefix
if name.startswith(prefix):
name = name[len(prefix):]
full_name = prefix + name
if scope:
def closure(name=name, full_name=full_name, function=f):
def wrapper(self, *args, **kwargs):
lazy_func = getattr(self.expression.ds.func, full_name)
args = (self.expression, ) + args
return lazy_func(*args, **kwargs)
return functools.wraps(function)(wrapper)
if as_property:
setattr(scopes[scope], name, property(closure()))
else:
setattr(scopes[scope], name, closure())
else:
def closure(name=name, full_name=full_name, function=f):
def wrapper(self, *args, **kwargs):
lazy_func = getattr(self.ds.func, full_name)
args = (self, ) + args
return lazy_func(*args, **kwargs)
return functools.wraps(function)(wrapper)
setattr(vaex.expression.Expression, name, closure())
vaex.expression.expression_namespace[prefix + name] = f
return f # we leave the original function as is
return wrapper | python | {
"resource": ""
} |
q267847 | fillna | test | def fillna(ar, value, fill_nan=True, fill_masked=True):
'''Returns an array where missing values are replaced by value.
If the dtype is object, nan values and 'nan' string values
are replaced by value when fill_nan==True.
'''
ar = ar if not isinstance(ar, column.Column) else ar.to_numpy()
if ar.dtype.kind in 'O' and fill_nan:
strings = ar.astype(str)
mask = strings == 'nan'
ar = ar.copy()
ar[mask] = value
elif ar.dtype.kind in 'f' and fill_nan:
mask = np.isnan(ar)
if np.any(mask):
ar = ar.copy()
ar[mask] = value
if fill_masked and np.ma.isMaskedArray(ar):
mask = ar.mask
if np.any(mask):
ar = ar.data.copy()
ar[mask] = value
return ar | python | {
"resource": ""
} |
q267848 | dt_dayofweek | test | def dt_dayofweek(x):
"""Obtain the day of the week with Monday=0 and Sunday=6
:returns: an expression containing the day of week.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.dayofweek
Expression = dt_dayofweek(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 0
1 3
2 3
"""
import pandas as pd
return pd.Series(x).dt.dayofweek.values | python | {
"resource": ""
} |
q267849 | dt_dayofyear | test | def dt_dayofyear(x):
"""The ordinal day of the year.
:returns: an expression containing the ordinal day of the year.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.dayofyear
Expression = dt_dayofyear(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 285
1 42
2 316
"""
import pandas as pd
return pd.Series(x).dt.dayofyear.values | python | {
"resource": ""
} |
q267850 | dt_is_leap_year | test | def dt_is_leap_year(x):
"""Check whether a year is a leap year.
:returns: an expression which evaluates to True if a year is a leap year, and to False otherwise.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.is_leap_year
Expression = dt_is_leap_year(date)
Length: 3 dtype: bool (expression)
----------------------------------
0 False
1 True
2 False
"""
import pandas as pd
return pd.Series(x).dt.is_leap_year.values | python | {
"resource": ""
} |
q267851 | dt_year | test | def dt_year(x):
"""Extracts the year out of a datetime sample.
:returns: an expression containing the year extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.year
Expression = dt_year(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 2009
1 2016
2 2015
"""
import pandas as pd
return pd.Series(x).dt.year.values | python | {
"resource": ""
} |
q267852 | dt_month | test | def dt_month(x):
"""Extracts the month out of a datetime sample.
:returns: an expression containing the month extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.month
Expression = dt_month(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 10
1 2
2 11
"""
import pandas as pd
return pd.Series(x).dt.month.values | python | {
"resource": ""
} |
q267853 | dt_month_name | test | def dt_month_name(x):
"""Returns the month names of a datetime sample in English.
:returns: an expression containing the month names extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.month_name
Expression = dt_month_name(date)
Length: 3 dtype: str (expression)
---------------------------------
0 October
1 February
2 November
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.month_name().values.astype(str) | python | {
"resource": ""
} |
q267854 | dt_day | test | def dt_day(x):
"""Extracts the day from a datetime sample.
:returns: an expression containing the day extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.day
Expression = dt_day(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 12
1 11
2 12
"""
import pandas as pd
return pd.Series(x).dt.day.values | python | {
"resource": ""
} |
q267855 | dt_day_name | test | def dt_day_name(x):
"""Returns the day names of a datetime sample in English.
:returns: an expression containing the day names extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.day_name
Expression = dt_day_name(date)
Length: 3 dtype: str (expression)
---------------------------------
0 Monday
1 Thursday
2 Thursday
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.day_name().values.astype(str) | python | {
"resource": ""
} |
q267856 | dt_weekofyear | test | def dt_weekofyear(x):
"""Returns the week ordinal of the year.
:returns: an expression containing the week ordinal of the year, extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.weekofyear
Expression = dt_weekofyear(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 42
1 6
2 46
"""
import pandas as pd
return pd.Series(x).dt.weekofyear.values | python | {
"resource": ""
} |
q267857 | dt_hour | test | def dt_hour(x):
"""Extracts the hour out of a datetime samples.
:returns: an expression containing the hour extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.hour
Expression = dt_hour(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 3
1 10
2 11
"""
import pandas as pd
return pd.Series(x).dt.hour.values | python | {
"resource": ""
} |
q267858 | dt_minute | test | def dt_minute(x):
"""Extracts the minute out of a datetime samples.
:returns: an expression containing the minute extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.minute
Expression = dt_minute(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 31
1 17
2 34
"""
import pandas as pd
return pd.Series(x).dt.minute.values | python | {
"resource": ""
} |
q267859 | dt_second | test | def dt_second(x):
"""Extracts the second out of a datetime samples.
:returns: an expression containing the second extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.second
Expression = dt_second(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 0
1 34
2 22
"""
import pandas as pd
return pd.Series(x).dt.second.values | python | {
"resource": ""
} |
q267860 | str_capitalize | test | def str_capitalize(x):
"""Capitalize the first letter of a string sample.
:returns: an expression containing the capitalized strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.capitalize()
Expression = str_capitalize(text)
Length: 5 dtype: str (expression)
---------------------------------
0 Something
1 Very pretty
2 Is coming
3 Our
4 Way.
"""
sl = _to_string_sequence(x).capitalize()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267861 | str_cat | test | def str_cat(x, other):
"""Concatenate two string columns on a row-by-row basis.
:param expression other: The expression of the other column to be concatenated.
:returns: an expression containing the concatenated columns.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.cat(df.text)
Expression = str_cat(text, text)
Length: 5 dtype: str (expression)
---------------------------------
0 SomethingSomething
1 very prettyvery pretty
2 is comingis coming
3 ourour
4 way.way.
"""
sl1 = _to_string_sequence(x)
sl2 = _to_string_sequence(other)
sl = sl1.concat(sl2)
return column.ColumnStringArrow.from_string_sequence(sl) | python | {
"resource": ""
} |
q267862 | str_contains | test | def str_contains(x, pattern, regex=True):
"""Check if a string pattern or regex is contained within a sample of a string column.
:param str pattern: A string or regex pattern
:param bool regex: If True,
:returns: an expression which is evaluated to True if the pattern is found in a given sample, and it is False otherwise.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.contains('very')
Expression = str_contains(text, 'very')
Length: 5 dtype: bool (expression)
----------------------------------
0 False
1 True
2 False
3 False
4 False
"""
return _to_string_sequence(x).search(pattern, regex) | python | {
"resource": ""
} |
q267863 | str_count | test | def str_count(x, pat, regex=False):
"""Count the occurences of a pattern in sample of a string column.
:param str pat: A string or regex pattern
:param bool regex: If True,
:returns: an expression containing the number of times a pattern is found in each sample.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.count(pat="et", regex=False)
Expression = str_count(text, pat='et', regex=False)
Length: 5 dtype: int64 (expression)
-----------------------------------
0 1
1 1
2 0
3 0
4 0
"""
return _to_string_sequence(x).count(pat, regex) | python | {
"resource": ""
} |
q267864 | str_find | test | def str_find(x, sub, start=0, end=None):
"""Returns the lowest indices in each string in a column, where the provided substring is fully contained between within a
sample. If the substring is not found, -1 is returned.
:param str sub: A substring to be found in the samples
:param int start:
:param int end:
:returns: an expression containing the lowest indices specifying the start of the substring.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.find(sub="et")
Expression = str_find(text, sub='et')
Length: 5 dtype: int64 (expression)
-----------------------------------
0 3
1 7
2 -1
3 -1
4 -1
"""
return _to_string_sequence(x).find(sub, start, 0 if end is None else end, end is None, True) | python | {
"resource": ""
} |
q267865 | str_get | test | def str_get(x, i):
"""Extract a character from each sample at the specified position from a string column.
Note that if the specified position is out of bound of the string sample, this method returns '', while pandas retunrs nan.
:param int i: The index location, at which to extract the character.
:returns: an expression containing the extracted characters.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.get(5)
Expression = str_get(text, 5)
Length: 5 dtype: str (expression)
---------------------------------
0 h
1 p
2 m
3
4
"""
x = _to_string_sequence(x)
if i == -1:
sl = x.slice_string_end(-1)
else:
sl = x.slice_string(i, i+1)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267866 | str_index | test | def str_index(x, sub, start=0, end=None):
"""Returns the lowest indices in each string in a column, where the provided substring is fully contained between within a
sample. If the substring is not found, -1 is returned. It is the same as `str.find`.
:param str sub: A substring to be found in the samples
:param int start:
:param int end:
:returns: an expression containing the lowest indices specifying the start of the substring.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.index(sub="et")
Expression = str_find(text, sub='et')
Length: 5 dtype: int64 (expression)
-----------------------------------
0 3
1 7
2 -1
3 -1
4 -1
"""
return str_find(x, sub, start, end) | python | {
"resource": ""
} |
q267867 | str_lower | test | def str_lower(x):
"""Converts string samples to lower case.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.lower()
Expression = str_lower(text)
Length: 5 dtype: str (expression)
---------------------------------
0 something
1 very pretty
2 is coming
3 our
4 way.
"""
sl = _to_string_sequence(x).lower()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267868 | str_lstrip | test | def str_lstrip(x, to_strip=None):
"""Remove leading characters from a string sample.
:param str to_strip: The string to be removed
:returns: an expression containing the modified string column.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.lstrip(to_strip='very ')
Expression = str_lstrip(text, to_strip='very ')
Length: 5 dtype: str (expression)
---------------------------------
0 Something
1 pretty
2 is coming
3 our
4 way.
"""
# in c++ we give empty string the same meaning as None
sl = _to_string_sequence(x).lstrip('' if to_strip is None else to_strip) if to_strip != '' else x
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267869 | str_pad | test | def str_pad(x, width, side='left', fillchar=' '):
"""Pad strings in a given column.
:param int width: The total width of the string
:param str side: If 'left' than pad on the left, if 'right' than pad on the right side the string.
:param str fillchar: The character used for padding.
:returns: an expression containing the padded strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.pad(width=10, side='left', fillchar='!')
Expression = str_pad(text, width=10, side='left', fillchar='!')
Length: 5 dtype: str (expression)
---------------------------------
0 !Something
1 very pretty
2 !is coming
3 !!!!!!!our
4 !!!!!!way.
"""
sl = _to_string_sequence(x).pad(width, fillchar, side in ['left', 'both'], side in ['right', 'both'])
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267870 | str_repeat | test | def str_repeat(x, repeats):
"""Duplicate each string in a column.
:param int repeats: number of times each string sample is to be duplicated.
:returns: an expression containing the duplicated strings
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.repeat(3)
Expression = str_repeat(text, 3)
Length: 5 dtype: str (expression)
---------------------------------
0 SomethingSomethingSomething
1 very prettyvery prettyvery pretty
2 is comingis comingis coming
3 ourourour
4 way.way.way.
"""
sl = _to_string_sequence(x).repeat(repeats)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267871 | str_rfind | test | def str_rfind(x, sub, start=0, end=None):
"""Returns the highest indices in each string in a column, where the provided substring is fully contained between within a
sample. If the substring is not found, -1 is returned.
:param str sub: A substring to be found in the samples
:param int start:
:param int end:
:returns: an expression containing the highest indices specifying the start of the substring.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.rfind(sub="et")
Expression = str_rfind(text, sub='et')
Length: 5 dtype: int64 (expression)
-----------------------------------
0 3
1 7
2 -1
3 -1
4 -1
"""
return _to_string_sequence(x).find(sub, start, 0 if end is None else end, end is None, False) | python | {
"resource": ""
} |
q267872 | str_rindex | test | def str_rindex(x, sub, start=0, end=None):
"""Returns the highest indices in each string in a column, where the provided substring is fully contained between within a
sample. If the substring is not found, -1 is returned. Same as `str.rfind`.
:param str sub: A substring to be found in the samples
:param int start:
:param int end:
:returns: an expression containing the highest indices specifying the start of the substring.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.rindex(sub="et")
Expression = str_rindex(text, sub='et')
Length: 5 dtype: int64 (expression)
-----------------------------------
0 3
1 7
2 -1
3 -1
4 -1
"""
return str_rfind(x, sub, start, end) | python | {
"resource": ""
} |
q267873 | str_rjust | test | def str_rjust(x, width, fillchar=' '):
"""Fills the left side of string samples with a specified character such that the strings are left-hand justified.
:param int width: The minimal width of the strings.
:param str fillchar: The character used for filling.
:returns: an expression containing the filled strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.rjust(width=10, fillchar='!')
Expression = str_rjust(text, width=10, fillchar='!')
Length: 5 dtype: str (expression)
---------------------------------
0 !Something
1 very pretty
2 !is coming
3 !!!!!!!our
4 !!!!!!way.
"""
sl = _to_string_sequence(x).pad(width, fillchar, True, False)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267874 | str_rstrip | test | def str_rstrip(x, to_strip=None):
"""Remove trailing characters from a string sample.
:param str to_strip: The string to be removed
:returns: an expression containing the modified string column.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.rstrip(to_strip='ing')
Expression = str_rstrip(text, to_strip='ing')
Length: 5 dtype: str (expression)
---------------------------------
0 Someth
1 very pretty
2 is com
3 our
4 way.
"""
# in c++ we give empty string the same meaning as None
sl = _to_string_sequence(x).rstrip('' if to_strip is None else to_strip) if to_strip != '' else x
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267875 | str_slice | test | def str_slice(x, start=0, stop=None): # TODO: support n
"""Slice substrings from each string element in a column.
:param int start: The start position for the slice operation.
:param int end: The stop position for the slice operation.
:returns: an expression containing the sliced substrings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.slice(start=2, stop=5)
Expression = str_pandas_slice(text, start=2, stop=5)
Length: 5 dtype: str (expression)
---------------------------------
0 met
1 ry
2 co
3 r
4 y.
"""
if stop is None:
sll = _to_string_sequence(x).slice_string_end(start)
else:
sll = _to_string_sequence(x).slice_string(start, stop)
return sll | python | {
"resource": ""
} |
q267876 | str_strip | test | def str_strip(x, to_strip=None):
"""Removes leading and trailing characters.
Strips whitespaces (including new lines), or a set of specified
characters from each string saple in a column, both from the left
right sides.
:param str to_strip: The characters to be removed. All combinations of the characters will be removed.
If None, it removes whitespaces.
:param returns: an expression containing the modified string samples.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.strip(to_strip='very')
Expression = str_strip(text, to_strip='very')
Length: 5 dtype: str (expression)
---------------------------------
0 Something
1 prett
2 is coming
3 ou
4 way.
"""
# in c++ we give empty string the same meaning as None
sl = _to_string_sequence(x).strip('' if to_strip is None else to_strip) if to_strip != '' else x
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267877 | str_title | test | def str_title(x):
"""Converts all string samples to titlecase.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.title()
Expression = str_title(text)
Length: 5 dtype: str (expression)
---------------------------------
0 Something
1 Very Pretty
2 Is Coming
3 Our
4 Way.
"""
sl = _to_string_sequence(x).title()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267878 | str_upper | test | def str_upper(x):
"""Converts all strings in a column to uppercase.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.upper()
Expression = str_upper(text)
Length: 5 dtype: str (expression)
---------------------------------
0 SOMETHING
1 VERY PRETTY
2 IS COMING
3 OUR
4 WAY.
"""
sl = _to_string_sequence(x).upper()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl) | python | {
"resource": ""
} |
q267879 | get_autotype | test | def get_autotype(arr):
"""
Attempts to return a numpy array converted to the most sensible dtype
Value errors will be caught and simply return the original array
Tries to make dtype int, then float, then no change
"""
try:
narr = arr.astype('float')
if (narr < sys.maxsize).all() and (narr % 1).sum() == 0:
return narr.astype('int')
else:
return narr
except ValueError:
return arr | python | {
"resource": ""
} |
q267880 | Struct.as_recarray | test | def as_recarray(self):
""" Convert into numpy recordarray """
dtype = [(k,v.dtype) for k,v in self.__dict__.iteritems()]
R = numpy.recarray(len(self.__dict__[k]),dtype=dtype)
for key in self.__dict__:
R[key] = self.__dict__[key]
return R | python | {
"resource": ""
} |
q267881 | store_properties | test | def store_properties(fh, props, comment=None, timestamp=True):
"""
Writes properties to the file in Java properties format.
:param fh: a writable file-like object
:param props: a mapping (dict) or iterable of key/value pairs
:param comment: comment to write to the beginning of the file
:param timestamp: boolean indicating whether to write a timestamp comment
"""
if comment is not None:
write_comment(fh, comment)
if timestamp:
write_comment(fh, time.strftime('%a %b %d %H:%M:%S %Z %Y'))
if hasattr(props, 'keys'):
for key in props:
write_property(fh, key, props[key])
else:
for key, value in props:
write_property(fh, key, value) | python | {
"resource": ""
} |
q267882 | write_comment | test | def write_comment(fh, comment):
"""
Writes a comment to the file in Java properties format.
Newlines in the comment text are automatically turned into a continuation
of the comment by adding a "#" to the beginning of each line.
:param fh: a writable file-like object
:param comment: comment string to write
"""
_require_string(comment, 'comments')
fh.write(_escape_comment(comment))
fh.write(b'\n') | python | {
"resource": ""
} |
q267883 | write_property | test | def write_property(fh, key, value):
"""
Write a single property to the file in Java properties format.
:param fh: a writable file-like object
:param key: the key to write
:param value: the value to write
"""
if key is COMMENT:
write_comment(fh, value)
return
_require_string(key, 'keys')
_require_string(value, 'values')
fh.write(_escape_key(key))
fh.write(b'=')
fh.write(_escape_value(value))
fh.write(b'\n') | python | {
"resource": ""
} |
q267884 | iter_properties | test | def iter_properties(fh, comments=False):
"""
Incrementally read properties from a Java .properties file.
Yields tuples of key/value pairs.
If ``comments`` is `True`, comments will be included with ``jprops.COMMENT``
in place of the key.
:param fh: a readable file-like object
:param comments: should include comments (default: False)
"""
for line in _property_lines(fh):
key, value = _split_key_value(line)
if key is not COMMENT:
key = _unescape(key)
elif not comments:
continue
yield key, _unescape(value) | python | {
"resource": ""
} |
q267885 | _universal_newlines | test | def _universal_newlines(fp):
"""
Wrap a file to convert newlines regardless of whether the file was opened
with the "universal newlines" option or not.
"""
# if file was opened with universal newline support we don't need to convert
if 'U' in getattr(fp, 'mode', ''):
for line in fp:
yield line
else:
for line in fp:
line = line.replace(b'\r\n', b'\n').replace(b'\r', b'\n')
for piece in line.split(b'\n'):
yield piece | python | {
"resource": ""
} |
q267886 | show_versions | test | def show_versions():
'''Return the version information for all librosa dependencies.'''
core_deps = ['audioread',
'numpy',
'scipy',
'sklearn',
'joblib',
'decorator',
'six',
'soundfile',
'resampy',
'numba']
extra_deps = ['numpydoc',
'sphinx',
'sphinx_rtd_theme',
'sphinxcontrib.versioning',
'sphinx-gallery',
'pytest',
'pytest-mpl',
'pytest-cov',
'matplotlib']
print('INSTALLED VERSIONS')
print('------------------')
print('python: {}\n'.format(sys.version))
print('librosa: {}\n'.format(version))
for dep in core_deps:
print('{}: {}'.format(dep, __get_mod_version(dep)))
print('')
for dep in extra_deps:
print('{}: {}'.format(dep, __get_mod_version(dep)))
pass | python | {
"resource": ""
} |
q267887 | rename_kw | test | def rename_kw(old_name, old_value, new_name, new_value,
version_deprecated, version_removed):
'''Handle renamed arguments.
Parameters
----------
old_name : str
old_value
The name and value of the old argument
new_name : str
new_value
The name and value of the new argument
version_deprecated : str
The version at which the old name became deprecated
version_removed : str
The version at which the old name will be removed
Returns
-------
value
- `new_value` if `old_value` of type `Deprecated`
- `old_value` otherwise
Warnings
--------
if `old_value` is not of type `Deprecated`
'''
if isinstance(old_value, Deprecated):
return new_value
else:
stack = inspect.stack()
dep_func = stack[1]
caller = stack[2]
warnings.warn_explicit("{:s}() keyword argument '{:s}' has been "
"renamed to '{:s}' in version {:}."
"\n\tThis alias will be removed in version "
"{:}.".format(dep_func[3],
old_name, new_name,
version_deprecated,
version_removed),
category=DeprecationWarning,
filename=caller[1],
lineno=caller[2])
return old_value | python | {
"resource": ""
} |
q267888 | set_fftlib | test | def set_fftlib(lib=None):
'''Set the FFT library used by librosa.
Parameters
----------
lib : None or module
Must implement an interface compatible with `numpy.fft`.
If `None`, reverts to `numpy.fft`.
Examples
--------
Use `pyfftw`:
>>> import pyfftw
>>> librosa.set_fftlib(pyfftw.interfaces.numpy_fft)
Reset to default `numpy` implementation
>>> librosa.set_fftlib()
'''
global __FFTLIB
if lib is None:
from numpy import fft
lib = fft
__FFTLIB = lib | python | {
"resource": ""
} |
q267889 | beat_track | test | def beat_track(input_file, output_csv):
'''Beat tracking function
:parameters:
- input_file : str
Path to input audio file (wav, mp3, m4a, flac, etc.)
- output_file : str
Path to save beat event timestamps as a CSV file
'''
print('Loading ', input_file)
y, sr = librosa.load(input_file, sr=22050)
# Use a default hop size of 512 samples @ 22KHz ~= 23ms
hop_length = 512
# This is the window length used by default in stft
print('Tracking beats')
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, hop_length=hop_length)
print('Estimated tempo: {:0.2f} beats per minute'.format(tempo))
# save output
# 'beats' will contain the frame numbers of beat events.
beat_times = librosa.frames_to_time(beats, sr=sr, hop_length=hop_length)
print('Saving output to ', output_csv)
librosa.output.times_csv(output_csv, beat_times)
print('done!') | python | {
"resource": ""
} |
q267890 | adjust_tuning | test | def adjust_tuning(input_file, output_file):
'''Load audio, estimate tuning, apply pitch correction, and save.'''
print('Loading ', input_file)
y, sr = librosa.load(input_file)
print('Separating harmonic component ... ')
y_harm = librosa.effects.harmonic(y)
print('Estimating tuning ... ')
# Just track the pitches associated with high magnitude
tuning = librosa.estimate_tuning(y=y_harm, sr=sr)
print('{:+0.2f} cents'.format(100 * tuning))
print('Applying pitch-correction of {:+0.2f} cents'.format(-100 * tuning))
y_tuned = librosa.effects.pitch_shift(y, sr, -tuning)
print('Saving tuned audio to: ', output_file)
librosa.output.write_wav(output_file, y_tuned, sr) | python | {
"resource": ""
} |
q267891 | frames_to_samples | test | def frames_to_samples(frames, hop_length=512, n_fft=None):
"""Converts frame indices to audio sample indices.
Parameters
----------
frames : number or np.ndarray [shape=(n,)]
frame index or vector of frame indices
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of `n_fft / 2`
to counteract windowing effects when using a non-centered STFT.
Returns
-------
times : number or np.ndarray
time (in samples) of each given frame number:
`times[i] = frames[i] * hop_length`
See Also
--------
frames_to_time : convert frame indices to time values
samples_to_frames : convert sample indices to frame indices
Examples
--------
>>> y, sr = librosa.load(librosa.util.example_audio_file())
>>> tempo, beats = librosa.beat.beat_track(y, sr=sr)
>>> beat_samples = librosa.frames_to_samples(beats)
"""
offset = 0
if n_fft is not None:
offset = int(n_fft // 2)
return (np.asanyarray(frames) * hop_length + offset).astype(int) | python | {
"resource": ""
} |
q267892 | samples_to_frames | test | def samples_to_frames(samples, hop_length=512, n_fft=None):
"""Converts sample indices into STFT frames.
Examples
--------
>>> # Get the frame numbers for every 256 samples
>>> librosa.samples_to_frames(np.arange(0, 22050, 256))
array([ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20,
21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34,
35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41,
42, 42, 43])
Parameters
----------
samples : int or np.ndarray [shape=(n,)]
sample index or vector of sample indices
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of `- n_fft / 2`
to counteract windowing effects in STFT.
.. note:: This may result in negative frame indices.
Returns
-------
frames : int or np.ndarray [shape=(n,), dtype=int]
Frame numbers corresponding to the given times:
`frames[i] = floor( samples[i] / hop_length )`
See Also
--------
samples_to_time : convert sample indices to time values
frames_to_samples : convert frame indices to sample indices
"""
offset = 0
if n_fft is not None:
offset = int(n_fft // 2)
samples = np.asanyarray(samples)
return np.floor((samples - offset) // hop_length).astype(int) | python | {
"resource": ""
} |
q267893 | time_to_frames | test | def time_to_frames(times, sr=22050, hop_length=512, n_fft=None):
"""Converts time stamps into STFT frames.
Parameters
----------
times : np.ndarray [shape=(n,)]
time (in seconds) or vector of time values
sr : number > 0 [scalar]
audio sampling rate
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of `- n_fft / 2`
to counteract windowing effects in STFT.
.. note:: This may result in negative frame indices.
Returns
-------
frames : np.ndarray [shape=(n,), dtype=int]
Frame numbers corresponding to the given times:
`frames[i] = floor( times[i] * sr / hop_length )`
See Also
--------
frames_to_time : convert frame indices to time values
time_to_samples : convert time values to sample indices
Examples
--------
Get the frame numbers for every 100ms
>>> librosa.time_to_frames(np.arange(0, 1, 0.1),
... sr=22050, hop_length=512)
array([ 0, 4, 8, 12, 17, 21, 25, 30, 34, 38])
"""
samples = time_to_samples(times, sr=sr)
return samples_to_frames(samples, hop_length=hop_length, n_fft=n_fft) | python | {
"resource": ""
} |
q267894 | midi_to_note | test | def midi_to_note(midi, octave=True, cents=False):
'''Convert one or more MIDI numbers to note strings.
MIDI numbers will be rounded to the nearest integer.
Notes will be of the format 'C0', 'C#0', 'D0', ...
Examples
--------
>>> librosa.midi_to_note(0)
'C-1'
>>> librosa.midi_to_note(37)
'C#2'
>>> librosa.midi_to_note(-2)
'A#-2'
>>> librosa.midi_to_note(104.7)
'A7'
>>> librosa.midi_to_note(104.7, cents=True)
'A7-30'
>>> librosa.midi_to_note(list(range(12, 24)))
['C0', 'C#0', 'D0', 'D#0', 'E0', 'F0', 'F#0', 'G0', 'G#0', 'A0', 'A#0', 'B0']
Parameters
----------
midi : int or iterable of int
Midi numbers to convert.
octave: bool
If True, include the octave number
cents: bool
If true, cent markers will be appended for fractional notes.
Eg, `midi_to_note(69.3, cents=True)` == `A4+03`
Returns
-------
notes : str or iterable of str
Strings describing each midi note.
Raises
------
ParameterError
if `cents` is True and `octave` is False
See Also
--------
midi_to_hz
note_to_midi
hz_to_note
'''
if cents and not octave:
raise ParameterError('Cannot encode cents without octave information.')
if not np.isscalar(midi):
return [midi_to_note(x, octave=octave, cents=cents) for x in midi]
note_map = ['C', 'C#', 'D', 'D#',
'E', 'F', 'F#', 'G',
'G#', 'A', 'A#', 'B']
note_num = int(np.round(midi))
note_cents = int(100 * np.around(midi - note_num, 2))
note = note_map[note_num % 12]
if octave:
note = '{:s}{:0d}'.format(note, int(note_num / 12) - 1)
if cents:
note = '{:s}{:+02d}'.format(note, note_cents)
return note | python | {
"resource": ""
} |
q267895 | hz_to_mel | test | def hz_to_mel(frequencies, htk=False):
"""Convert Hz to Mels
Examples
--------
>>> librosa.hz_to_mel(60)
0.9
>>> librosa.hz_to_mel([110, 220, 440])
array([ 1.65, 3.3 , 6.6 ])
Parameters
----------
frequencies : number or np.ndarray [shape=(n,)] , float
scalar or array of frequencies
htk : bool
use HTK formula instead of Slaney
Returns
-------
mels : number or np.ndarray [shape=(n,)]
input frequencies in Mels
See Also
--------
mel_to_hz
"""
frequencies = np.asanyarray(frequencies)
if htk:
return 2595.0 * np.log10(1.0 + frequencies / 700.0)
# Fill in the linear part
f_min = 0.0
f_sp = 200.0 / 3
mels = (frequencies - f_min) / f_sp
# Fill in the log-scale part
min_log_hz = 1000.0 # beginning of log region (Hz)
min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels)
logstep = np.log(6.4) / 27.0 # step size for log region
if frequencies.ndim:
# If we have array data, vectorize
log_t = (frequencies >= min_log_hz)
mels[log_t] = min_log_mel + np.log(frequencies[log_t]/min_log_hz) / logstep
elif frequencies >= min_log_hz:
# If we have scalar data, heck directly
mels = min_log_mel + np.log(frequencies / min_log_hz) / logstep
return mels | python | {
"resource": ""
} |
q267896 | mel_to_hz | test | def mel_to_hz(mels, htk=False):
"""Convert mel bin numbers to frequencies
Examples
--------
>>> librosa.mel_to_hz(3)
200.
>>> librosa.mel_to_hz([1,2,3,4,5])
array([ 66.667, 133.333, 200. , 266.667, 333.333])
Parameters
----------
mels : np.ndarray [shape=(n,)], float
mel bins to convert
htk : bool
use HTK formula instead of Slaney
Returns
-------
frequencies : np.ndarray [shape=(n,)]
input mels in Hz
See Also
--------
hz_to_mel
"""
mels = np.asanyarray(mels)
if htk:
return 700.0 * (10.0**(mels / 2595.0) - 1.0)
# Fill in the linear scale
f_min = 0.0
f_sp = 200.0 / 3
freqs = f_min + f_sp * mels
# And now the nonlinear scale
min_log_hz = 1000.0 # beginning of log region (Hz)
min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels)
logstep = np.log(6.4) / 27.0 # step size for log region
if mels.ndim:
# If we have vector data, vectorize
log_t = (mels >= min_log_mel)
freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel))
elif mels >= min_log_mel:
# If we have scalar data, check directly
freqs = min_log_hz * np.exp(logstep * (mels - min_log_mel))
return freqs | python | {
"resource": ""
} |
q267897 | fft_frequencies | test | def fft_frequencies(sr=22050, n_fft=2048):
'''Alternative implementation of `np.fft.fftfreq`
Parameters
----------
sr : number > 0 [scalar]
Audio sampling rate
n_fft : int > 0 [scalar]
FFT window size
Returns
-------
freqs : np.ndarray [shape=(1 + n_fft/2,)]
Frequencies `(0, sr/n_fft, 2*sr/n_fft, ..., sr/2)`
Examples
--------
>>> librosa.fft_frequencies(sr=22050, n_fft=16)
array([ 0. , 1378.125, 2756.25 , 4134.375,
5512.5 , 6890.625, 8268.75 , 9646.875, 11025. ])
'''
return np.linspace(0,
float(sr) / 2,
int(1 + n_fft//2),
endpoint=True) | python | {
"resource": ""
} |
q267898 | cqt_frequencies | test | def cqt_frequencies(n_bins, fmin, bins_per_octave=12, tuning=0.0):
"""Compute the center frequencies of Constant-Q bins.
Examples
--------
>>> # Get the CQT frequencies for 24 notes, starting at C2
>>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2'))
array([ 65.406, 69.296, 73.416, 77.782, 82.407, 87.307,
92.499, 97.999, 103.826, 110. , 116.541, 123.471,
130.813, 138.591, 146.832, 155.563, 164.814, 174.614,
184.997, 195.998, 207.652, 220. , 233.082, 246.942])
Parameters
----------
n_bins : int > 0 [scalar]
Number of constant-Q bins
fmin : float > 0 [scalar]
Minimum frequency
bins_per_octave : int > 0 [scalar]
Number of bins per octave
tuning : float in `[-0.5, +0.5)`
Deviation from A440 tuning in fractional bins (cents)
Returns
-------
frequencies : np.ndarray [shape=(n_bins,)]
Center frequency for each CQT bin
"""
correction = 2.0**(float(tuning) / bins_per_octave)
frequencies = 2.0**(np.arange(0, n_bins, dtype=float) / bins_per_octave)
return correction * fmin * frequencies | python | {
"resource": ""
} |
q267899 | mel_frequencies | test | def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0, htk=False):
"""Compute an array of acoustic frequencies tuned to the mel scale.
The mel scale is a quasi-logarithmic function of acoustic frequency
designed such that perceptually similar pitch intervals (e.g. octaves)
appear equal in width over the full hearing range.
Because the definition of the mel scale is conditioned by a finite number
of subjective psychoaoustical experiments, several implementations coexist
in the audio signal processing literature [1]_. By default, librosa replicates
the behavior of the well-established MATLAB Auditory Toolbox of Slaney [2]_.
According to this default implementation, the conversion from Hertz to mel is
linear below 1 kHz and logarithmic above 1 kHz. Another available implementation
replicates the Hidden Markov Toolkit [3]_ (HTK) according to the following formula:
`mel = 2595.0 * np.log10(1.0 + f / 700.0).`
The choice of implementation is determined by the `htk` keyword argument: setting
`htk=False` leads to the Auditory toolbox implementation, whereas setting it `htk=True`
leads to the HTK implementation.
.. [1] Umesh, S., Cohen, L., & Nelson, D. Fitting the mel scale.
In Proc. International Conference on Acoustics, Speech, and Signal Processing
(ICASSP), vol. 1, pp. 217-220, 1998.
.. [2] Slaney, M. Auditory Toolbox: A MATLAB Toolbox for Auditory
Modeling Work. Technical Report, version 2, Interval Research Corporation, 1998.
.. [3] Young, S., Evermann, G., Gales, M., Hain, T., Kershaw, D., Liu, X.,
Moore, G., Odell, J., Ollason, D., Povey, D., Valtchev, V., & Woodland, P.
The HTK book, version 3.4. Cambridge University, March 2009.
See Also
--------
hz_to_mel
mel_to_hz
librosa.feature.melspectrogram
librosa.feature.mfcc
Parameters
----------
n_mels : int > 0 [scalar]
Number of mel bins.
fmin : float >= 0 [scalar]
Minimum frequency (Hz).
fmax : float >= 0 [scalar]
Maximum frequency (Hz).
htk : bool
If True, use HTK formula to convert Hz to mel.
Otherwise (False), use Slaney's Auditory Toolbox.
Returns
-------
bin_frequencies : ndarray [shape=(n_mels,)]
Vector of n_mels frequencies in Hz which are uniformly spaced on the Mel
axis.
Examples
--------
>>> librosa.mel_frequencies(n_mels=40)
array([ 0. , 85.317, 170.635, 255.952,
341.269, 426.586, 511.904, 597.221,
682.538, 767.855, 853.173, 938.49 ,
1024.856, 1119.114, 1222.042, 1334.436,
1457.167, 1591.187, 1737.532, 1897.337,
2071.84 , 2262.393, 2470.47 , 2697.686,
2945.799, 3216.731, 3512.582, 3835.643,
4188.417, 4573.636, 4994.285, 5453.621,
5955.205, 6502.92 , 7101.009, 7754.107,
8467.272, 9246.028, 10096.408, 11025. ])
"""
# 'Center freqs' of mel bands - uniformly spaced between limits
min_mel = hz_to_mel(fmin, htk=htk)
max_mel = hz_to_mel(fmax, htk=htk)
mels = np.linspace(min_mel, max_mel, n_mels)
return mel_to_hz(mels, htk=htk) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.