_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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 ?
| 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"
| 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())
| python | {
"resource": ""
} |
q267803 | DataFrame.delete_virtual_column | test | def delete_virtual_column(self, name):
"""Deletes a virtual column from a | 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) | python | {
"resource": ""
} |
q267805 | DataFrame.delete_variable | test | def delete_variable(self, name):
"""Deletes a variable from a DataFrame."""
del self.variables[name]
| 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)
| 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
| 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 = | 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
| 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))):
| 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']
"""
| 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:
| 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):
| 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()
| 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
| 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 | 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
| 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 | 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)
| 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
| 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]
| python | {
"resource": ""
} |
q267822 | DataFrame.selection_can_redo | test | def selection_can_redo(self, name="default"):
"""Can selection name be redone?"""
| 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):
| 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) | 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
| 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 | 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)) | 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:
| 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)
| 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
| 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:
"""
| 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:
| 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:
| python | {
"resource": ""
} |
q267834 | DataFrame._find_valid_name | test | def _find_valid_name(self, initial_name):
'''Finds a non-colliding name by optional postfixing'''
| 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 | 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')
| 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) | 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)
| 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
| 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 | 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:
| 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 | 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 | 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)
| python | {
"resource": ""
} |
q267845 | patch | test | def patch(f):
'''Adds method f to the DataFrame class'''
name = f.__name__
| 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
| 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)
| 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)
| 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)
| 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)
| 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
| 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
| 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)
| 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
| 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)
| 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
| 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
| 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
| 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
| 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)
---------------------------------
| 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)
| 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 | 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
| 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 | 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
| 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
| 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 | 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)
---------------------------------
| 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.
| 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)
---------------------------------
| 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 | 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
| 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.
| 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 | 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. | 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
| 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)
---------------------------------
| 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)
--------------------------------- | 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')
| 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()]
| 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)
| 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
| 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
| 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)
"""
| 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: | 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']
| 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 {:}."
| 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)
| 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 | 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))
| 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
| 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.
| 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] = | 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 | 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)
| 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 | 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,)]
| 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 | 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 : | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.