code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
for i in range(0, len(iterable), n):
yield iterable[i:i + n] | def chunks(iterable, n) | Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 | 2.001762 | 1.729681 | 1.157301 |
for el in iterable:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
yield el | def flatten(iterable) | flat a iterable. https://stackoverflow.com/a/2158532 | 1.789359 | 1.593579 | 1.122856 |
factory = FestivalFactory(lang=lang)
return factory.iter_festival_countdown(countdown, date_obj) | def iter_festival_countdown(countdown: Optional[int] = None, date_obj: MDate = None,
lang: str = 'zh-Hans') -> FestivalCountdownIterable | Return countdown of festivals. | 4.664915 | 3.670011 | 1.27109 |
year = year or self.year
if year:
return self._resolve(year)
raise ValueError('Unable resolve the date without a specified year.') | def resolve(self, year: int = YEAR_ANY) -> MDate | Return the date object in the solar / lunar year.
:param year:
:return: | 8.515882 | 9.17271 | 0.928393 |
if self.date_class == date:
return self.resolve(year)
else:
solar_date = LCalendars.cast_date(self.resolve(year), date)
offset = solar_date.year - year
if offset:
solar_date = LCalendars.cast_date(self.resolve(year - offset), date)
return solar_date | def resolve_solar(self, year: int) -> date | Return the date object in a solar year.
:param year:
:return: | 4.504385 | 4.453941 | 1.011326 |
leap_month, leap_days = _parse_leap(year_info)
res = leap_days
for month in range(1, 13):
res += (year_info >> (16 - month)) % 2 + 29
return res | def parse_year_days(year_info) | Parse year days from a year info. | 5.749176 | 5.346709 | 1.075274 |
# info => month, days, leap
leap_month, leap_days = _parse_leap(year_info)
months = [(i, 0) for i in range(1, 13)]
if leap_month > 0:
months.insert(leap_month, (leap_month, 1))
for month, leap in months:
if leap:
days = leap_days
else:
days = (year_info >> (16 - month)) % 2 + 29
yield month, days, leap | def _iter_year_month(year_info) | Iter the month days in a lunar year. | 3.620408 | 3.339998 | 1.083955 |
if year == 2101:
days = [5, 20]
else:
days = TermUtils.parse_term_days(year)
term_index1 = 2 * (month - 1)
term_index2 = 2 * (month - 1) + 1
day1 = days[term_index1]
day2 = days[term_index2]
if day == day1:
term_name = TERMS_CN[term_index1]
elif day == day2:
term_name = TERMS_CN[term_index2]
else:
term_name = None
next_gz_month = day >= day1
return term_name, next_gz_month | def get_term_info(year, month, day) | Parse solar term and stem-branch year/month/day from a solar date.
(sy, sm, sd) => (term, next_gz_month)
term for year 2101,:2101.1.5(初六) 小寒 2101.1.20(廿一) 大寒 | 3.358083 | 2.645292 | 1.269457 |
return TextUtils.STEMS[offset % 10] + TextUtils.BRANCHES[offset % 12] | def get_gz_cn(offset: int) -> str | Get n-th(0-based) GanZhi | 15.932878 | 11.424667 | 1.394603 |
solar_date = MIN_SOLAR_DATE + datetime.timedelta(days=self._offset)
sy, sm, sd = solar_date.year, solar_date.month, solar_date.day
s_offset = (datetime.date(sy, sm, sd) - MIN_SOLAR_DATE).days
gz_year = TextUtils.STEMS[(self.year - 4) % 10] + TextUtils.BRANCHES[(self.year - 4) % 12]
gz_day = TextUtils.get_gz_cn((s_offset + 40) % 60)
term_name, next_gz_month = TermUtils.get_term_info(sy, sm, sd)
if next_gz_month:
gz_month = TextUtils.get_gz_cn((sy - 1900) * 12 + sm + 12)
else:
gz_month = TextUtils.get_gz_cn((sy - 1900) * 12 + sm + 11)
return gz_year, gz_month, gz_day, term_name | def _get_gz_ymd(self) | (sy, sm, sd) -> term / gz_year / gz_month / gz_day | 3.073848 | 2.959138 | 1.038765 |
def _getter(item):
if getter:
custom_getter = partial(getter, key=key)
return custom_getter(item)
else:
return partial(bget, key=key, default=default)(item)
return map(_getter, iterable) | def ifetch_single(iterable, key, default=EMPTY, getter=None) | getter() g(item, key):pass | 4.147286 | 4.116065 | 1.007585 |
birthday = LCalendars.cast_date(birthday, date)
if today:
today = LCalendars.cast_date(today, date)
else:
today = date.today()
return today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day)) | def actual_age_solar(birthday, today=None) | See more at https://stackoverflow.com/questions/2217488/age-from-birthdate-in-python/9754466#9754466
:param birthday:
:param today:
:return: | 2.656529 | 2.84001 | 0.935394 |
model['typedefs'] = {}
# bitmasks and basetypes
bitmasks = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'bitmask']
basetypes = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'basetype']
for typedef in bitmasks + basetypes:
if not typedef.get('type'):
continue
model['typedefs'][typedef['name']] = typedef['type']
# handles
handles = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'handle']
for handle in handles:
if 'name' not in handle or 'type' not in handle:
continue
n = handle['name']
t = handle['type']
if t == 'VK_DEFINE_HANDLE':
model['typedefs']['struct %s_T' % n] = '*%s' % n
if t == 'VK_DEFINE_HANDLE':
model['typedefs'][n] = 'uint64_t'
# custom plaform dependant
for name in ['Display', 'xcb_connection_t', 'wl_display', 'wl_surface',
'MirConnection', 'MirSurface', 'ANativeWindow',
'SECURITY_ATTRIBUTES']:
model['typedefs'][name] = 'struct %s' % name
model['typedefs'].update({
'Window': 'uint32_t', 'VisualID': 'uint32_t',
'xcb_window_t': 'uint32_t', 'xcb_visualid_t': 'uint32_t'
}) | def model_typedefs(vk, model) | Fill the model with typedefs
model['typedefs'] = {'name': 'type', ...} | 3.096022 | 2.994365 | 1.033949 |
model['enums'] = {}
# init enums dict
enums_type = [x['@name'] for x in vk['registry']['types']['type']
if x.get('@category') == 'enum']
for name in enums_type:
model['enums'][name] = {}
# create enums
enums = [x for x in vk['registry']['enums']
if x.get('@type') in ('enum', 'bitmask')]
for enum in enums:
name = enum['@name']
t = enum.get('@type')
# enum may have no enums (because of extension)
if not enum.get('enum'):
continue
if t in ('enum', 'bitmask'):
# add attr to enum
for attr in enum['enum']:
if '@bitpos' in attr:
num_val = int(attr['@bitpos'], 0)
num_val = 1 << num_val
val = '0x%08x' % num_val
elif '@value' in attr:
val = attr['@value']
model['enums'][name][attr['@name']] = val
# Add computed value
def ext_name(name, extension):
if extension:
return name + '_' + extension
return name
extension = next(iter([x for x in VENDOR_EXTENSIONS
if name.lower().endswith(x)]), '').upper()
standard_name = inflection.underscore(name).upper()
if extension:
standard_name = standard_name.split(extension)[0][:-1]
if t == 'bitmask':
en = ext_name(standard_name, '_MAX_ENUM')
model['enums'][name][en] = 0x7FFFFFFF
else:
values = [int(x, 0) for x in model['enums'][name].values()]
begin_attr = ext_name(standard_name, '_BEGIN_RANGE')
end_attr = ext_name(standard_name, '_END_RANGE')
size_attr = ext_name(standard_name, '_RANGE_SIZE')
max_attr = ext_name(standard_name, '_MAX_ENUM')
model['enums'][name][begin_attr] = min(values)
model['enums'][name][end_attr] = max(values)
model['enums'][name][size_attr] = max(values) - min(values) + 1
model['enums'][name][max_attr] = 0x7FFFFFFF
# Enum in features
ext_base = 1000000000
ext_blocksize = 1000
# base + (ext - 1) * blocksize + offset
for feature in vk['registry']['feature']:
for require in feature['require']:
if not 'enum' in require:
continue
for enum in require['enum']:
if not '@extnumber' in enum:
continue
n1 = int(enum['@extnumber'])
n2 = int(enum['@offset'])
extend = enum['@extends']
val = ext_base + (n1 - 1) * ext_blocksize + n2
model['enums'][extend][enum['@name']] = val | def model_enums(vk, model) | Fill the model with enums
model['enums'] = {'name': {'item_name': 'item_value'...}, ...} | 2.960946 | 2.970748 | 0.996701 |
model['macros'] = {}
# API Macros
macros = [x for x in vk['registry']['enums']
if x.get('@type') not in ('bitmask', 'enum')]
# TODO: Check theses values
special_values = {'1000.0f': '1000.0',
'(~0U)': 0xffffffff,
'(~0ULL)': -1,
'(~0U-1)': 0xfffffffe,
'(~0U-2)': 0xfffffffd}
for macro in macros[0]['enum']:
if '@name' not in macro or '@value' not in macro:
continue
name = macro['@name']
value = macro['@value']
if value in special_values:
value = special_values[value]
model['macros'][name] = value
# Extension Macros
for ext in get_extensions_filtered(vk):
model['macros'][ext['@name']] = 1
for req in ext['require']:
for enum in req['enum']:
ename = enum['@name']
evalue = parse_constant(enum, int(ext['@number']))
if enum.get('@extends') == 'VkResult':
model['enums']['VkResult'][ename] = evalue
else:
model['macros'][ename] = evalue | def model_macros(vk, model) | Fill the model with macros
model['macros'] = {'name': value, ...} | 4.434983 | 4.38555 | 1.011272 |
model['funcpointers'] = {}
funcs = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'funcpointer']
structs = [x for x in vk['registry']['types']['type']
if x.get('@category') == 'struct']
for f in funcs:
pfn_name = f['name']
for s in structs:
if 'member' not in s:
continue
for m in s['member']:
if m['type'] == pfn_name:
struct_name = s['@name']
model['funcpointers'][pfn_name] = struct_name | def model_funcpointers(vk, model) | Fill the model with function pointer
model['funcpointers'] = {'pfn_name': 'struct_name'} | 3.130166 | 2.718625 | 1.151378 |
model['exceptions'] = {}
model['errors'] = {}
all_codes = model['enums']['VkResult']
success_names = set()
error_names = set()
commands = [x for x in vk['registry']['commands']['command']]
for command in commands:
successes = command.get('@successcodes', '').split(',')
errors = command.get('@errorcodes', '').split(',')
success_names.update(successes)
error_names.update(errors)
for key, value in all_codes.items():
if key.startswith('VK_RESULT') or key == 'VK_SUCCESS':
continue
name = inflection.camelize(key.lower())
if key in success_names:
model['exceptions'][value] = name
elif key in error_names:
model['errors'][value] = name
else:
print('Warning: return code %s unused' % key) | def model_exceptions(vk, model) | Fill the model with exceptions and errors
model['exceptions'] = {val: 'name',...}
model['errors'] = {val: 'name',...} | 3.649147 | 3.3555 | 1.087512 |
model['constructors'] = []
structs = [x for x in vk['registry']['types']['type']
if x.get('@category') in {'struct', 'union'}]
def parse_len(member):
mlen = member.get('@len')
if not mlen:
return None
if ',' in mlen:
mlen = mlen.split(',')[0]
if 'latex' in mlen or 'null-terminated' in mlen:
return None
return mlen
for struct in structs:
if 'member' not in struct:
continue
model['constructors'].append({
'name': struct['@name'],
'members': [{
'name': x['name'],
'type': x['type'],
'default': x.get('@values'),
'len': parse_len(x)
} for x in struct['member']]
}) | def model_constructors(vk, model) | Fill the model with constructors
model['constructors'] = [{'name': 'x', 'members': [{'name': 'y'}].}] | 3.272239 | 3.194216 | 1.024426 |
def get_vk_extension_functions():
names = set()
for extension in get_extensions_filtered(vk):
for req in extension['require']:
if 'command' not in req:
continue
for command in req['command']:
cn = command['@name']
names.add(cn)
# add alias command too
for alias, n in model['alias'].items():
if n == cn:
names.add(alias)
return names
def get_count_param(command):
for param in command['param']:
if param['type'] + param.get('#text', '') == 'uint32_t*':
return param
return None
def member_has_str(name):
c = next(iter([x for x in model['constructors']
if x['name'] == name]), None)
if c and any(['char' in x['type'] for x in c['members']]):
return True
return False
def format_member(member):
type_name = member['type']
if '#text' in member:
text = member['#text'].replace('const ', '').strip()
type_name += ' ' + text
return {'name': member['name'],
'type': member['type'],
'none': member['name'] in NULL_MEMBERS,
'force_array': True if '@len' in member else False,
'to_create': False,
'has_str': member_has_str(member['type'])}
def format_return_member(member):
t = member['type']
static_count = None
if '@len' in member and '::' in member['@len']:
lens = member['@len'].split('::')
static_count = {'key': lens[0], 'value': lens[1]}
is_handle = t in get_handle_names(vk)
is_enum = t in get_enum_names(vk)
is_struct = t in get_struct_names(vk)
return {'name': member['name'],
'type': t,
'handle': is_handle,
'enum': is_enum,
'struct': is_struct,
'static_count': static_count,
'has_str': member_has_str(member['type'])}
ALLOCATE_PREFIX = ('vkCreate', 'vkGet', 'vkEnumerate', 'vkAllocate',
'vkMap', 'vkAcquire')
ALLOCATE_EXCEPTION = ('vkGetFenceStatus', 'vkGetEventStatus',
'vkGetQueryPoolResults',
'vkGetPhysicalDeviceXlibPresentationSupportKHR')
COUNT_EXCEPTION = ('vkAcquireNextImageKHR', 'vkEnumerateInstanceVersion')
model['functions'] = []
model['extension_functions'] = []
functions = [f for f in vk['registry']['commands']['command']]
extension_function_names = get_vk_extension_functions()
for function in functions:
if '@alias' in function:
continue
fname = function['proto']['name']
ftype = function['proto']['type']
if fname in CUSTOM_FUNCTIONS:
continue
if type(function['param']) is not list:
function['param'] = [function['param']]
count_param = get_count_param(function)
if fname in COUNT_EXCEPTION:
count_param = None
is_allocate = any([fname.startswith(a) for a in ALLOCATE_PREFIX])
is_count = is_allocate and count_param is not None
if fname in ALLOCATE_EXCEPTION or ftype == 'VkBool32':
is_allocate = is_count = False
members = []
for member in function['param']:
members.append(format_member(member))
return_member = None
if is_allocate:
return_member = format_return_member(function['param'][-1])
members[-1]['to_create'] = True
if is_count:
members[-2]['to_create'] = True
f = {
'name': fname,
'members': members,
'allocate': is_allocate,
'count': is_count,
'return_boolean': True if ftype == 'VkBool32' else False,
'return_result': True if ftype == 'VkResult' else False,
'return_member': return_member,
'is_extension': fname in extension_function_names
}
model['functions'].append(f) | def model_functions(vk, model) | Fill the model with functions | 2.9882 | 2.999527 | 0.996224 |
model['ext_functions'] = {'instance': {}, 'device': {}}
# invert the alias to better lookup
alias = {v: k for k, v in model['alias'].items()}
for extension in get_extensions_filtered(vk):
for req in extension['require']:
if not req.get('command'):
continue
ext_type = extension['@type']
for x in req['command']:
name = x['@name']
if name in alias.keys():
model['ext_functions'][ext_type][name] = alias[name]
else:
model['ext_functions'][ext_type][name] = name | def model_ext_functions(vk, model) | Fill the model with extensions functions | 4.460197 | 4.40966 | 1.011461 |
model['alias'] = {}
# types
for s in vk['registry']['types']['type']:
if s.get('@category', None) == 'handle' and s.get('@alias'):
model['alias'][s['@alias']] = s['@name']
# commands
for c in vk['registry']['commands']['command']:
if c.get('@alias'):
model['alias'][c['@alias']] = c['@name'] | def model_alias(vk, model) | Fill the model with alias since V1 | 3.864502 | 3.634897 | 1.063167 |
# Force extension require to be a list
for ext in get_extensions_filtered(vk):
req = ext['require']
if not isinstance(req, list):
ext['require'] = [req] | def format_vk(vk) | Format vk before using it | 7.734885 | 8.318834 | 0.929804 |
model = {}
vk = init()
format_vk(vk)
model_alias(vk, model)
model_typedefs(vk, model)
model_enums(vk, model)
model_macros(vk, model)
model_funcpointers(vk, model)
model_exceptions(vk, model)
model_constructors(vk, model)
model_functions(vk, model)
model_ext_functions(vk, model)
env = jinja2.Environment(
autoescape=False,
trim_blocks=True,
lstrip_blocks=True,
loader=jinja2.FileSystemLoader(HERE)
)
out_file = path.join(HERE, path.pardir, 'vulkan', '_vulkan.py')
with open(out_file, 'w') as out:
out.write(env.get_template('vulkan.template.py').render(model=model)) | def generate_py() | Generate the python output file | 2.988096 | 2.978889 | 1.003091 |
include_libc_path = path.join(HERE, 'fake_libc_include')
include_vulkan_path = path.join(HERE, 'vulkan_include')
out_file = path.join(HERE, path.pardir, 'vulkan', 'vulkan.cdef.h')
header = path.join(include_vulkan_path, 'vulkan.h')
command = ['cpp',
'-std=c99',
'-P',
'-nostdinc',
'-I' + include_libc_path,
'-I' + include_vulkan_path,
'-o' + out_file,
'-DVK_USE_PLATFORM_XCB_KHR',
'-DVK_USE_PLATFORM_WAYLAND_KHR',
'-DVK_USE_PLATFORM_ANDROID_KHR',
'-DVK_USE_PLATFORM_WIN32_KHR',
'-DVK_USE_PLATFORM_XLIB_KHR',
header]
subprocess.run(command, check=True) | def generate_cdef() | Generate the cdef output file | 2.696687 | 2.681022 | 1.005843 |
if apps.ready:
# We're running in a real Django unit test, don't do anything.
return
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
django.setup()
mock_django_connection(disabled_features) | def mock_django_setup(settings_module, disabled_features=None) | Must be called *AT IMPORT TIME* to pretend that Django is set up.
This is useful for running tests without using the Django test runner.
This must be called before any Django models are imported, or they will
complain. Call this from a module in the calling project at import time,
then be sure to import that module at the start of all mock test modules.
Another option is to call it from the test package's init file, so it runs
before all the test modules are imported.
:param settings_module: the module name of the Django settings file,
like 'myapp.settings'
:param disabled_features: a list of strings that should be marked as
*False* on the connection features list. All others will default
to True. | 4.06262 | 4.824241 | 0.842126 |
db = connections.databases['default']
db['PASSWORD'] = '****'
db['USER'] = '**Database disabled for unit tests**'
ConnectionHandler.__getitem__ = MagicMock(name='mock_connection')
# noinspection PyUnresolvedReferences
mock_connection = ConnectionHandler.__getitem__.return_value
if disabled_features:
for feature in disabled_features:
setattr(mock_connection.features, feature, False)
mock_ops = mock_connection.ops
# noinspection PyUnusedLocal
def compiler(queryset, connection, using, **kwargs):
result = MagicMock(name='mock_connection.ops.compiler()')
# noinspection PyProtectedMember
result.execute_sql.side_effect = NotSupportedError(
"Mock database tried to execute SQL for {} model.".format(
queryset.model._meta.object_name))
result.has_results.side_effect = result.execute_sql.side_effect
return result
mock_ops.compiler.return_value.side_effect = compiler
mock_ops.integer_field_range.return_value = (-sys.maxsize - 1, sys.maxsize)
mock_ops.max_name_length.return_value = sys.maxsize
Model.refresh_from_db = Mock() | def mock_django_connection(disabled_features=None) | Overwrite the Django database configuration with a mocked version.
This is a helper function that does the actual monkey patching. | 4.06852 | 4.045625 | 1.005659 |
for model in models:
yield model
# noinspection PyProtectedMember
for parent in model._meta.parents.keys():
for parent_model in find_all_models((parent,)):
yield parent_model | def find_all_models(models) | Yield all models and their parents. | 3.512642 | 2.596108 | 1.353041 |
patchers = []
for model in find_all_models(models):
if isinstance(model.save, Mock):
# already mocked, so skip it
continue
model_name = model._meta.object_name
patchers.append(_patch_save(model, model_name))
if hasattr(model, 'objects'):
patchers.append(_patch_objects(model, model_name))
for related_object in chain(model._meta.related_objects,
model._meta.many_to_many):
name = related_object.name
if name not in model.__dict__ and related_object.one_to_many:
name += '_set'
if name in model.__dict__:
# Only mock direct relations, not inherited ones.
if getattr(model, name, None):
patchers.append(_patch_relation(
model, name, related_object
))
return PatcherChain(patchers, pass_mocks=False) | def mocked_relations(*models) | Mock all related field managers to make pure unit tests possible.
The resulting patcher can be used just like one from the mock module:
As a test method decorator, a test class decorator, a context manager,
or by just calling start() and stop().
@mocked_relations(Dataset):
def test_dataset(self):
dataset = Dataset()
check = dataset.content_checks.create() # returns a ContentCheck object | 3.445121 | 3.552434 | 0.969792 |
# noinspection PyUnusedLocal
def absorb_mocks(test_case, *args):
return target(test_case)
should_absorb = not (self.pass_mocks or isinstance(target, type))
result = absorb_mocks if should_absorb else target
for patcher in self.patchers:
result = patcher(result)
return result | def decorate_callable(self, target) | Called as a decorator. | 5.318318 | 4.975063 | 1.068995 |
return issubclass(arr.dtype.type, np.integer) or np.allclose(arr, np.round(arr)) | def _is_array_integer(arr) | Returns True if an array contains integers (integer type or near-int
float values) and False otherwise.
>>> _is_array_integer(np.arange(10))
True
>>> _is_array_integer(np.arange(7.0, 20.0, 1.0))
True
>>> _is_array_integer(np.arange(0, 1, 0.1))
False | 3.745403 | 5.394047 | 0.694359 |
if not column_fn:
return column_fn
if not callable(column_fn):
raise TypeError('column functions must be callable')
@functools.wraps(column_fn)
def wrapped(column):
try:
return column_fn(column)
except TypeError:
if isinstance(column, np.ndarray):
return column.dtype.type() # A typed zero value
else:
raise
return wrapped | def _zero_on_type_error(column_fn) | Wrap a function on an np.ndarray to return 0 on a type error. | 2.886444 | 2.54285 | 1.135121 |
assert len(rows) > 0
if not _is_non_string_iterable(partials):
# Convert partials to tuple for comparison against row slice later
partials = [(partial,) for partial in partials]
# Construct mapping of partials to values in rows
mapping = {}
for row in rows:
mapping[tuple(row[:-1])] = row[-1]
if zero is None:
# Try to infer zero from given row values.
array = np.array(tuple(mapping.values()))
if len(array.shape) == 1:
zero = array.dtype.type()
return np.array([mapping.get(partial, zero) for partial in partials]) | def _fill_with_zeros(partials, rows, zero=None) | Find and return values from rows for all partials. In cases where no
row matches a partial, zero is assumed as value. For a row, the first
(n-1) fields are assumed to be the partial, and the last field,
the value, where n is the total number of fields in each row. It is
assumed that there is a unique row for each partial.
partials -- single field values or tuples of field values
rows -- table rows
zero -- value used when no rows match a particular partial | 4.16481 | 4.101922 | 1.015332 |
if len(label_list) == 0:
return []
elif not _is_non_string_iterable(label_list[0]):
# Assume everything is a label. If not, it'll be caught later.
return label_list
elif len(label_list) == 1:
return label_list[0]
else:
raise ValueError("Labels {} contain more than list.".format(label_list),
"Pass just one list of labels.") | def _varargs_labels_as_list(label_list) | Return a list of labels for a list of labels or singleton list of list
of labels. | 4.192717 | 4.14324 | 1.011942 |
assert len(values) > 0
first, rest = values[0], values[1:]
for v in rest:
assert v == first
return first | def _assert_same(values) | Assert that all values are identical and return the unique value. | 2.966774 | 2.625654 | 1.129918 |
if not collect.__name__.startswith('<'):
return label + ' ' + collect.__name__
else:
return label | def _collected_label(collect, label) | Label of a collected column. | 6.412184 | 6.666797 | 0.961809 |
if isinstance(value, str):
return False
if hasattr(value, '__iter__'):
return True
if isinstance(value, collections.abc.Sequence):
return True
return False | def _is_non_string_iterable(value) | Whether a value is iterable. | 2.463776 | 2.20966 | 1.115002 |
if ticks is None:
ticks = axis.get_xticks()
if (np.array(ticks) == np.rint(ticks)).all():
ticks = np.rint(ticks).astype(np.int)
if max([len(str(tick)) for tick in ticks]) > max_width:
axis.set_xticklabels(ticks, rotation='vertical') | def _vertical_x(axis, ticks=None, max_width=5) | Switch labels to vertical if they are long. | 2.852728 | 2.428169 | 1.174847 |
warnings.warn("Table.empty(labels) is deprecated. Use Table(labels)", FutureWarning)
if labels is None:
return cls()
values = [[] for label in labels]
return cls(values, labels) | def empty(cls, labels=None) | Creates an empty table. Column labels are optional. [Deprecated]
Args:
``labels`` (None or list): If ``None``, a table with 0
columns is created.
If a list, each element is a column label in a table with
0 rows.
Returns:
A new instance of ``Table``. | 4.696503 | 4.588119 | 1.023623 |
warnings.warn("Table.from_rows is deprecated. Use Table(labels).with_rows(...)", FutureWarning)
return cls(labels).with_rows(rows) | def from_rows(cls, rows, labels) | Create a table from a sequence of rows (fixed-length sequences). [Deprecated] | 5.509145 | 4.527276 | 1.216879 |
if not records:
return cls()
labels = sorted(list(records[0].keys()))
columns = [[rec[label] for rec in records] for label in labels]
return cls().with_columns(zip(labels, columns)) | def from_records(cls, records) | Create a table from a sequence of records (dicts with fixed keys). | 4.182784 | 3.812028 | 1.09726 |
warnings.warn("Table.from_columns_dict is deprecated. Use Table().with_columns(...)", FutureWarning)
return cls().with_columns(columns.items()) | def from_columns_dict(cls, columns) | Create a table from a mapping of column labels to column values. [Deprecated] | 6.627221 | 5.079414 | 1.304721 |
# Look for .csv at the end of the path; use "," as a separator if found
try:
path = urllib.parse.urlparse(filepath_or_buffer).path
if 'data8.berkeley.edu' in filepath_or_buffer:
raise ValueError('data8.berkeley.edu requires authentication, '
'which is not supported.')
except AttributeError:
path = filepath_or_buffer
try:
if 'sep' not in vargs and path.endswith('.csv'):
vargs['sep'] = ','
except AttributeError:
pass
df = pandas.read_table(filepath_or_buffer, *args, **vargs)
return cls.from_df(df) | def read_table(cls, filepath_or_buffer, *args, **vargs) | Read a table from a file or web address.
filepath_or_buffer -- string or file handle / StringIO; The string
could be a URL. Valid URL schemes include http,
ftp, s3, and file. | 3.9743 | 3.857967 | 1.030154 |
table = type(self)()
for label, column in zip(self.labels, columns):
self._add_column_and_format(table, label, column)
return table | def _with_columns(self, columns) | Create a table from a sequence of columns, copying column labels. | 5.522501 | 4.167133 | 1.325252 |
label = self._as_label(label)
table[label] = column
if label in self._formats:
table._formats[label] = self._formats[label] | def _add_column_and_format(self, table, label, column) | Add a column to table, copying the formatter from self. | 3.918236 | 3.313173 | 1.182624 |
t = cls()
labels = df.columns
for label in df.columns:
t.append_column(label, df[label])
return t | def from_df(cls, df) | Convert a Pandas DataFrame into a Table. | 4.995504 | 3.882743 | 1.286591 |
return cls().with_columns([(f, arr[f]) for f in arr.dtype.names]) | def from_array(cls, arr) | Convert a structured NumPy array into a Table. | 8.675438 | 6.984962 | 1.242016 |
if (isinstance(index_or_label, str)
and index_or_label not in self.labels):
raise ValueError(
'The column "{}" is not in the table. The table contains '
'these columns: {}'
.format(index_or_label, ', '.join(self.labels))
)
if (isinstance(index_or_label, int)
and not 0 <= index_or_label < len(self.labels)):
raise ValueError(
'The index {} is not in the table. Only indices between '
'0 and {} are valid'
.format(index_or_label, len(self.labels) - 1)
)
return self._columns[self._as_label(index_or_label)] | def column(self, index_or_label) | Return the values of a column as an array.
table.column(label) is equivalent to table[label].
>>> tiles = Table().with_columns(
... 'letter', make_array('c', 'd'),
... 'count', make_array(2, 4),
... )
>>> list(tiles.column('letter'))
['c', 'd']
>>> tiles.column(1)
array([2, 4])
Args:
label (int or str): The index or label of a column
Returns:
An instance of ``numpy.array``.
Raises:
``ValueError``: When the ``index_or_label`` is not in the table. | 2.069267 | 2.148914 | 0.962936 |
dtypes = [col.dtype for col in self.columns]
if len(set(dtypes)) > 1:
dtype = object
else:
dtype = None
return np.array(self.columns, dtype=dtype).T | def values(self) | Return data in `self` as a numpy array.
If all columns are the same dtype, the resulting array
will have this dtype. If there are >1 dtypes in columns,
then the resulting array will have dtype `object`. | 3.894844 | 2.716207 | 1.433928 |
if not column_or_columns:
return np.array([fn(row) for row in self.rows])
else:
if len(column_or_columns) == 1 and \
_is_non_string_iterable(column_or_columns[0]):
warnings.warn(
"column lists are deprecated; pass each as an argument", FutureWarning)
column_or_columns = column_or_columns[0]
rows = zip(*self.select(*column_or_columns).columns)
return np.array([fn(*row) for row in rows]) | def apply(self, fn, *column_or_columns) | Apply ``fn`` to each element or elements of ``column_or_columns``.
If no ``column_or_columns`` provided, `fn`` is applied to each row.
Args:
``fn`` (function) -- The function to apply.
``column_or_columns``: Columns containing the arguments to ``fn``
as either column labels (``str``) or column indices (``int``).
The number of columns must match the number of arguments
that ``fn`` expects.
Raises:
``ValueError`` -- if ``column_label`` is not an existing
column in the table.
``TypeError`` -- if insufficent number of ``column_label`` passed
to ``fn``.
Returns:
An array consisting of results of applying ``fn`` to elements
specified by ``column_label`` in each row.
>>> t = Table().with_columns(
... 'letter', make_array('a', 'b', 'c', 'z'),
... 'count', make_array(9, 3, 3, 1),
... 'points', make_array(1, 2, 2, 10))
>>> t
letter | count | points
a | 9 | 1
b | 3 | 2
c | 3 | 2
z | 1 | 10
>>> t.apply(lambda x: x - 1, 'points')
array([0, 1, 1, 9])
>>> t.apply(lambda x, y: x * y, 'count', 'points')
array([ 9, 6, 6, 10])
>>> t.apply(lambda x: x - 1, 'count', 'points')
Traceback (most recent call last):
...
TypeError: <lambda>() takes 1 positional argument but 2 were given
>>> t.apply(lambda x: x - 1, 'counts')
Traceback (most recent call last):
...
ValueError: The column "counts" is not in the table. The table contains these columns: letter, count, points
Whole rows are passed to the function if no columns are specified.
>>> t.apply(lambda row: row[1] * 2)
array([18, 6, 6, 2]) | 3.468616 | 3.914643 | 0.886062 |
if inspect.isclass(formatter):
formatter = formatter()
if callable(formatter) and not hasattr(formatter, 'format_column'):
formatter = _formats.FunctionFormatter(formatter)
if not hasattr(formatter, 'format_column'):
raise Exception('Expected Formatter or function: ' + str(formatter))
for label in self._as_labels(column_or_columns):
if formatter.converts_values:
self[label] = formatter.convert_column(self[label])
self._formats[label] = formatter
return self | def set_format(self, column_or_columns, formatter) | Set the format of a column. | 3.916272 | 3.901913 | 1.00368 |
self._columns.move_to_end(column_label, last=False)
return self | def move_to_start(self, column_label) | Move a column to the first in order. | 5.252047 | 4.396432 | 1.194616 |
if not row_or_table:
return
if isinstance(row_or_table, Table):
t = row_or_table
columns = list(t.select(self.labels)._columns.values())
n = t.num_rows
else:
if (len(list(row_or_table)) != self.num_columns):
raise Exception('Row should have '+ str(self.num_columns) + " columns")
columns, n = [[value] for value in row_or_table], 1
for i, column in enumerate(self._columns):
if self.num_rows:
self._columns[column] = np.append(self[column], columns[i])
else:
self._columns[column] = np.array(columns[i])
self._num_rows += n
return self | def append(self, row_or_table) | Append a row or all rows of a table. An appended table must have all
columns of self. | 2.957577 | 2.927928 | 1.010127 |
# TODO(sam): Allow append_column to take in a another table, copying
# over formatter as needed.
if not isinstance(label, str):
raise ValueError('The column label must be a string, but a '
'{} was given'.format(label.__class__.__name__))
if not isinstance(values, np.ndarray):
# Coerce a single value to a sequence
if not _is_non_string_iterable(values):
values = [values] * max(self.num_rows, 1)
values = np.array(tuple(values))
if self.num_rows != 0 and len(values) != self.num_rows:
raise ValueError('Column length mismatch. New column does not have '
'the same number of rows as table.')
else:
self._num_rows = len(values)
self._columns[label] = values | def append_column(self, label, values) | Appends a column to the table or replaces a column.
``__setitem__`` is aliased to this method:
``table.append_column('new_col', make_array(1, 2, 3))`` is equivalent to
``table['new_col'] = make_array(1, 2, 3)``.
Args:
``label`` (str): The label of the new column.
``values`` (single value or list/array): If a single value, every
value in the new column is ``values``.
If a list or array, the new column contains the values in
``values``, which must be the same length as the table.
Returns:
Original table with new or replaced column
Raises:
``ValueError``: If
- ``label`` is not a string.
- ``values`` is a list/array and does not have the same length
as the number of rows in the table.
>>> table = Table().with_columns(
... 'letter', make_array('a', 'b', 'c', 'z'),
... 'count', make_array(9, 3, 3, 1),
... 'points', make_array(1, 2, 2, 10))
>>> table
letter | count | points
a | 9 | 1
b | 3 | 2
c | 3 | 2
z | 1 | 10
>>> table.append_column('new_col1', make_array(10, 20, 30, 40))
>>> table
letter | count | points | new_col1
a | 9 | 1 | 10
b | 3 | 2 | 20
c | 3 | 2 | 30
z | 1 | 10 | 40
>>> table.append_column('new_col2', 'hello')
>>> table
letter | count | points | new_col1 | new_col2
a | 9 | 1 | 10 | hello
b | 3 | 2 | 20 | hello
c | 3 | 2 | 30 | hello
z | 1 | 10 | 40 | hello
>>> table.append_column(123, make_array(1, 2, 3, 4))
Traceback (most recent call last):
...
ValueError: The column label must be a string, but a int was given
>>> table.append_column('bad_col', [1, 2])
Traceback (most recent call last):
...
ValueError: Column length mismatch. New column does not have the same number of rows as table. | 4.466433 | 3.77545 | 1.18302 |
if isinstance(column_label, numbers.Integral):
column_label = self._as_label(column_label)
if isinstance(column_label, str) and isinstance(new_label, str):
column_label, new_label = [column_label], [new_label]
if len(column_label) != len(new_label):
raise ValueError('Invalid arguments. column_label and new_label '
'must be of equal length.')
old_to_new = dict(zip(column_label, new_label)) # maps old labels to new ones
for label in column_label:
if not (label in self.labels):
raise ValueError('Invalid labels. Column labels must '
'already exist in table in order to be replaced.')
rewrite = lambda s: old_to_new[s] if s in old_to_new else s
columns = [(rewrite(s), c) for s, c in self._columns.items()]
self._columns = collections.OrderedDict(columns)
for label in self._formats:
# TODO(denero) Error when old and new columns share a name
if label in column_label:
formatter = self._formats.pop(label)
self._formats[old_to_new[label]] = formatter
return self | def relabel(self, column_label, new_label) | Changes the label(s) of column(s) specified by ``column_label`` to
labels in ``new_label``.
Args:
``column_label`` -- (single str or array of str) The label(s) of
columns to be changed to ``new_label``.
``new_label`` -- (single str or array of str): The label name(s)
of columns to replace ``column_label``.
Raises:
``ValueError`` -- if ``column_label`` is not in table, or if
``column_label`` and ``new_label`` are not of equal length.
``TypeError`` -- if ``column_label`` and/or ``new_label`` is not
``str``.
Returns:
Original table with ``new_label`` in place of ``column_label``.
>>> table = Table().with_columns(
... 'points', make_array(1, 2, 3),
... 'id', make_array(12345, 123, 5123))
>>> table.relabel('id', 'yolo')
points | yolo
1 | 12,345
2 | 123
3 | 5,123
>>> table.relabel(make_array('points', 'yolo'),
... make_array('red', 'blue'))
red | blue
1 | 12,345
2 | 123
3 | 5,123
>>> table.relabel(make_array('red', 'green', 'blue'),
... make_array('cyan', 'magenta', 'yellow', 'key'))
Traceback (most recent call last):
...
ValueError: Invalid arguments. column_label and new_label must be of equal length. | 3.144957 | 3.035968 | 1.035899 |
if not row_or_row_indices:
return
if isinstance(row_or_row_indices, int):
rows_remove = [row_or_row_indices]
else:
rows_remove = row_or_row_indices
for col in self._columns:
self._columns[col] = [elem for i, elem in enumerate(self[col]) if i not in rows_remove]
return self | def remove(self, row_or_row_indices) | Removes a row or multiple rows of a table in place. | 2.200516 | 2.126427 | 1.034842 |
table = type(self)()
for label in self.labels:
if shallow:
column = self[label]
else:
column = np.copy(self[label])
self._add_column_and_format(table, label, column)
return table | def copy(self, *, shallow=False) | Return a copy of a table. | 4.400815 | 3.542172 | 1.242406 |
labels = self._varargs_as_labels(column_or_columns)
table = type(self)()
for label in labels:
self._add_column_and_format(table, label, np.copy(self[label]))
return table | def select(self, *column_or_columns) | Return a table with only the columns in ``column_or_columns``.
Args:
``column_or_columns``: Columns to select from the ``Table`` as
either column labels (``str``) or column indices (``int``).
Returns:
A new instance of ``Table`` containing only selected columns.
The columns of the new ``Table`` are in the order given in
``column_or_columns``.
Raises:
``KeyError`` if any of ``column_or_columns`` are not in the table.
>>> flowers = Table().with_columns(
... 'Number of petals', make_array(8, 34, 5),
... 'Name', make_array('lotus', 'sunflower', 'rose'),
... 'Weight', make_array(10, 5, 6)
... )
>>> flowers
Number of petals | Name | Weight
8 | lotus | 10
34 | sunflower | 5
5 | rose | 6
>>> flowers.select('Number of petals', 'Weight')
Number of petals | Weight
8 | 10
34 | 5
5 | 6
>>> flowers # original table unchanged
Number of petals | Name | Weight
8 | lotus | 10
34 | sunflower | 5
5 | rose | 6
>>> flowers.select(0, 2)
Number of petals | Weight
8 | 10
34 | 5
5 | 6 | 6.914381 | 8.823013 | 0.783676 |
exclude = _varargs_labels_as_list(column_or_columns)
return self.select([c for (i, c) in enumerate(self.labels)
if i not in exclude and c not in exclude]) | def drop(self, *column_or_columns) | Return a Table with only columns other than selected label or
labels.
Args:
``column_or_columns`` (string or list of strings): The header
names or indices of the columns to be dropped.
``column_or_columns`` must be an existing header name, or a
valid column index.
Returns:
An instance of ``Table`` with given columns removed.
>>> t = Table().with_columns(
... 'burgers', make_array('cheeseburger', 'hamburger', 'veggie burger'),
... 'prices', make_array(6, 5, 5),
... 'calories', make_array(743, 651, 582))
>>> t
burgers | prices | calories
cheeseburger | 6 | 743
hamburger | 5 | 651
veggie burger | 5 | 582
>>> t.drop('prices')
burgers | calories
cheeseburger | 743
hamburger | 651
veggie burger | 582
>>> t.drop(['burgers', 'calories'])
prices
6
5
5
>>> t.drop('burgers', 'calories')
prices
6
5
5
>>> t.drop([0, 2])
prices
6
5
5
>>> t.drop(0, 2)
prices
6
5
5
>>> t.drop(1)
burgers | calories
cheeseburger | 743
hamburger | 651
veggie burger | 582 | 7.080813 | 9.481523 | 0.746801 |
column = self._get_column(column_or_label)
if distinct:
_, row_numbers = np.unique(column, return_index=True)
else:
row_numbers = np.argsort(column, axis=0, kind='mergesort')
assert (row_numbers < self.num_rows).all(), row_numbers
if descending:
row_numbers = np.array(row_numbers[::-1])
return self.take(row_numbers) | def sort(self, column_or_label, descending=False, distinct=False) | Return a Table of rows sorted according to the values in a column.
Args:
``column_or_label``: the column whose values are used for sorting.
``descending``: if True, sorting will be in descending, rather than
ascending order.
``distinct``: if True, repeated values in ``column_or_label`` will
be omitted.
Returns:
An instance of ``Table`` containing rows sorted based on the values
in ``column_or_label``.
>>> marbles = Table().with_columns(
... "Color", make_array("Red", "Green", "Blue", "Red", "Green", "Green"),
... "Shape", make_array("Round", "Rectangular", "Rectangular", "Round", "Rectangular", "Round"),
... "Amount", make_array(4, 6, 12, 7, 9, 2),
... "Price", make_array(1.30, 1.30, 2.00, 1.75, 1.40, 1.00))
>>> marbles
Color | Shape | Amount | Price
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Blue | Rectangular | 12 | 2
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Green | Round | 2 | 1
>>> marbles.sort("Amount")
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Blue | Rectangular | 12 | 2
>>> marbles.sort("Amount", descending = True)
Color | Shape | Amount | Price
Blue | Rectangular | 12 | 2
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Green | Rectangular | 6 | 1.3
Red | Round | 4 | 1.3
Green | Round | 2 | 1
>>> marbles.sort(3) # the Price column
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Blue | Rectangular | 12 | 2
>>> marbles.sort(3, distinct = True)
Color | Shape | Amount | Price
Green | Round | 2 | 1
Red | Round | 4 | 1.3
Green | Rectangular | 9 | 1.4
Red | Round | 7 | 1.75
Blue | Rectangular | 12 | 2 | 2.617388 | 3.432199 | 0.762598 |
# Assume that a call to group with a list of labels is a call to groups
if _is_non_string_iterable(column_or_label) and \
len(column_or_label) != self._num_rows:
return self.groups(column_or_label, collect)
self = self.copy(shallow=True)
collect = _zero_on_type_error(collect)
# Remove column used for grouping
column = self._get_column(column_or_label)
if isinstance(column_or_label, str) or isinstance(column_or_label, numbers.Integral):
column_label = self._as_label(column_or_label)
del self[column_label]
else:
column_label = self._unused_label('group')
# Group by column
groups = self.index_by(column)
keys = sorted(groups.keys())
# Generate grouped columns
if collect is None:
labels = [column_label, 'count' if column_label != 'count' else self._unused_label('count')]
columns = [keys, [len(groups[k]) for k in keys]]
else:
columns, labels = [], []
for i, label in enumerate(self.labels):
labels.append(_collected_label(collect, label))
c = [collect(np.array([row[i] for row in groups[k]])) for k in keys]
columns.append(c)
grouped = type(self)().with_columns(zip(labels, columns))
assert column_label == self._unused_label(column_label)
grouped[column_label] = keys
grouped.move_to_start(column_label)
return grouped | def group(self, column_or_label, collect=None) | Group rows by unique values in a column; count or aggregate others.
Args:
``column_or_label``: values to group (column label or index, or array)
``collect``: a function applied to values in other columns for each group
Returns:
A Table with each row corresponding to a unique value in ``column_or_label``,
where the first column contains the unique values from ``column_or_label``, and the
second contains counts for each of the unique values. If ``collect`` is
provided, a Table is returned with all original columns, each containing values
calculated by first grouping rows according to ``column_or_label``, then applying
``collect`` to each set of grouped values in the other columns.
Note:
The grouped column will appear first in the result table. If ``collect`` does not
accept arguments with one of the column types, that column will be empty in the resulting
table.
>>> marbles = Table().with_columns(
... "Color", make_array("Red", "Green", "Blue", "Red", "Green", "Green"),
... "Shape", make_array("Round", "Rectangular", "Rectangular", "Round", "Rectangular", "Round"),
... "Amount", make_array(4, 6, 12, 7, 9, 2),
... "Price", make_array(1.30, 1.30, 2.00, 1.75, 1.40, 1.00))
>>> marbles
Color | Shape | Amount | Price
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Blue | Rectangular | 12 | 2
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Green | Round | 2 | 1
>>> marbles.group("Color") # just gives counts
Color | count
Blue | 1
Green | 3
Red | 2
>>> marbles.group("Color", max) # takes the max of each grouping, in each column
Color | Shape max | Amount max | Price max
Blue | Rectangular | 12 | 2
Green | Round | 9 | 1.4
Red | Round | 7 | 1.75
>>> marbles.group("Shape", sum) # sum doesn't make sense for strings
Shape | Color sum | Amount sum | Price sum
Rectangular | | 27 | 4.7
Round | | 13 | 4.05 | 3.753934 | 3.936067 | 0.953727 |
# Assume that a call to groups with one label is a call to group
if not _is_non_string_iterable(labels):
return self.group(labels, collect=collect)
collect = _zero_on_type_error(collect)
columns = []
labels = self._as_labels(labels)
for label in labels:
if label not in self.labels:
raise ValueError("All labels must exist in the table")
columns.append(self._get_column(label))
grouped = self.group(list(zip(*columns)), lambda s: s)
grouped._columns.popitem(last=False) # Discard the column of tuples
# Flatten grouping values and move them to front
counts = [len(v) for v in grouped[0]]
for label in labels[::-1]:
grouped[label] = grouped.apply(_assert_same, label)
grouped.move_to_start(label)
# Aggregate other values
if collect is None:
count = 'count' if 'count' not in labels else self._unused_label('count')
return grouped.select(labels).with_column(count, counts)
else:
for label in grouped.labels:
if label in labels:
continue
column = [collect(v) for v in grouped[label]]
del grouped[label]
grouped[_collected_label(collect, label)] = column
return grouped | def groups(self, labels, collect=None) | Group rows by multiple columns, count or aggregate others.
Args:
``labels``: list of column names (or indices) to group on
``collect``: a function applied to values in other columns for each group
Returns: A Table with each row corresponding to a unique combination of values in
the columns specified in ``labels``, where the first columns are those
specified in ``labels``, followed by a column of counts for each of the unique
values. If ``collect`` is provided, a Table is returned with all original
columns, each containing values calculated by first grouping rows according to
to values in the ``labels`` column, then applying ``collect`` to each set of
grouped values in the other columns.
Note:
The grouped columns will appear first in the result table. If ``collect`` does not
accept arguments with one of the column types, that column will be empty in the resulting
table.
>>> marbles = Table().with_columns(
... "Color", make_array("Red", "Green", "Blue", "Red", "Green", "Green"),
... "Shape", make_array("Round", "Rectangular", "Rectangular", "Round", "Rectangular", "Round"),
... "Amount", make_array(4, 6, 12, 7, 9, 2),
... "Price", make_array(1.30, 1.30, 2.00, 1.75, 1.40, 1.00))
>>> marbles
Color | Shape | Amount | Price
Red | Round | 4 | 1.3
Green | Rectangular | 6 | 1.3
Blue | Rectangular | 12 | 2
Red | Round | 7 | 1.75
Green | Rectangular | 9 | 1.4
Green | Round | 2 | 1
>>> marbles.groups(["Color", "Shape"])
Color | Shape | count
Blue | Rectangular | 1
Green | Rectangular | 2
Green | Round | 1
Red | Round | 2
>>> marbles.groups(["Color", "Shape"], sum)
Color | Shape | Amount sum | Price sum
Blue | Rectangular | 12 | 2
Green | Rectangular | 15 | 2.7
Green | Round | 2 | 1
Red | Round | 11 | 3.05 | 5.349337 | 5.397839 | 0.991014 |
pivot_columns = _as_labels(pivot_columns)
selected = self.select(pivot_columns + [value_column])
grouped = selected.groups(pivot_columns, collect=lambda x:x)
# refine bins by taking a histogram over all the data
if bins is not None:
vargs['bins'] = bins
_, rbins = np.histogram(self[value_column],**vargs)
# create a table with these bins a first column and counts for each group
vargs['bins'] = rbins
binned = type(self)().with_column('bin',rbins)
for group in grouped.rows:
col_label = "-".join(map(str,group[0:-1]))
col_vals = group[-1]
counts,_ = np.histogram(col_vals,**vargs)
binned[col_label] = np.append(counts,0)
return binned | def pivot_bin(self, pivot_columns, value_column, bins=None, **vargs) | Form a table with columns formed by the unique tuples in pivot_columns
containing counts per bin of the values associated with each tuple in the value_column.
By default, bins are chosen to contain all values in the value_column. The
following named arguments from numpy.histogram can be applied to
specialize bin widths:
Args:
``bins`` (int or sequence of scalars): If bins is an int,
it defines the number of equal-width bins in the given range
(10, by default). If bins is a sequence, it defines the bin
edges, including the rightmost edge, allowing for non-uniform
bin widths.
``range`` ((float, float)): The lower and upper range of
the bins. If not provided, range contains all values in the
table. Values outside the range are ignored.
``normed`` (bool): If False, the result will contain the number of
samples in each bin. If True, the result is normalized such that
the integral over the range is 1. | 5.253665 | 5.960618 | 0.881396 |
rows, labels = [], labels or self.labels
for row in self.rows:
[rows.append((getattr(row, key), k, v)) for k, v in row.asdict().items()
if k != key and k in labels]
return type(self)([key, 'column', 'value']).with_rows(rows) | def stack(self, key, labels=None) | Takes k original columns and returns two columns, with col. 1 of
all column names and col. 2 of all associated data. | 5.897116 | 5.517445 | 1.068813 |
names = [op.__name__ for op in ops]
ops = [_zero_on_type_error(op) for op in ops]
columns = [[op(column) for op in ops] for column in self.columns]
table = type(self)().with_columns(zip(self.labels, columns))
stats = table._unused_label('statistic')
table[stats] = names
table.move_to_start(stats)
return table | def stats(self, ops=(min, max, np.median, sum)) | Compute statistics for each column and place them in a table. | 5.77 | 5.087626 | 1.134124 |
if isinstance(index_or_label, str):
return index_or_label
if isinstance(index_or_label, numbers.Integral):
return self.labels[index_or_label]
else:
raise ValueError(str(index_or_label) + ' is not a label or index') | def _as_label(self, index_or_label) | Convert index to label. | 2.085261 | 1.950896 | 1.068873 |
original = label
existing = self.labels
i = 2
while label in existing:
label = '{}_{}'.format(original, i)
i += 1
return label | def _unused_label(self, label) | Generate an unused label. | 4.350905 | 3.77134 | 1.153676 |
c = column_or_label
if isinstance(c, collections.Hashable) and c in self.labels:
return self[c]
elif isinstance(c, numbers.Integral):
return self[c]
elif isinstance(c, str):
raise ValueError('label "{}" not in labels {}'.format(c, self.labels))
else:
assert len(c) == self.num_rows, 'column length mismatch'
return c | def _get_column(self, column_or_label) | Convert label to column and check column length. | 3.255455 | 2.853604 | 1.140822 |
percentiles = [[_util.percentile(p, column)] for column in self.columns]
return self._with_columns(percentiles) | def percentile(self, p) | Return a new table with one row containing the pth percentile for
each column.
Assumes that each column only contains one type of value.
Returns a new table with one row and the same column labels.
The row contains the pth percentile of the original column, where the
pth percentile of a column is the smallest value that at at least as
large as the p% of numbers in the column.
>>> table = Table().with_columns(
... 'count', make_array(9, 3, 3, 1),
... 'points', make_array(1, 2, 2, 10))
>>> table
count | points
9 | 1
3 | 2
3 | 2
1 | 10
>>> table.percentile(80)
count | points
9 | 10 | 9.326922 | 15.407571 | 0.605347 |
n = self.num_rows
if k is None:
k = n
index = np.random.choice(n, k, replace=with_replacement, p=weights)
columns = [[c[i] for i in index] for c in self.columns]
sample = self._with_columns(columns)
return sample | def sample(self, k=None, with_replacement=True, weights=None) | Return a new table where k rows are randomly sampled from the
original table.
Args:
``k`` -- specifies the number of rows (``int``) to be sampled from
the table. Default is k equal to number of rows in the table.
``with_replacement`` -- (``bool``) By default True;
Samples ``k`` rows with replacement from table, else samples
``k`` rows without replacement.
``weights`` -- Array specifying probability the ith row of the
table is sampled. Defaults to None, which samples each row
with equal probability. ``weights`` must be a valid probability
distribution -- i.e. an array the length of the number of rows,
summing to 1.
Raises:
ValueError -- if ``weights`` is not length equal to number of rows
in the table; or, if ``weights`` does not sum to 1.
Returns:
A new instance of ``Table`` with ``k`` rows resampled.
>>> jobs = Table().with_columns(
... 'job', make_array('a', 'b', 'c', 'd'),
... 'wage', make_array(10, 20, 15, 8))
>>> jobs
job | wage
a | 10
b | 20
c | 15
d | 8
>>> jobs.sample() # doctest: +SKIP
job | wage
b | 20
b | 20
a | 10
d | 8
>>> jobs.sample(with_replacement=True) # doctest: +SKIP
job | wage
d | 8
b | 20
c | 15
a | 10
>>> jobs.sample(k = 2) # doctest: +SKIP
job | wage
b | 20
c | 15
>>> ws = make_array(0.5, 0.5, 0, 0)
>>> jobs.sample(k=2, with_replacement=True, weights=ws) # doctest: +SKIP
job | wage
a | 10
a | 10
>>> jobs.sample(k=2, weights=make_array(1, 0, 1, 0))
Traceback (most recent call last):
...
ValueError: probabilities do not sum to 1
# Weights must be length of table.
>>> jobs.sample(k=2, weights=make_array(1, 0, 0))
Traceback (most recent call last):
...
ValueError: a and p must have same size | 2.886283 | 3.516151 | 0.820864 |
dist = self._get_column(distribution)
total = sum(dist)
assert total > 0 and np.all(dist >= 0), 'Counts or a distribution required'
dist = dist/sum(dist)
sample = np.random.multinomial(k, dist)
if proportions:
sample = sample / sum(sample)
label = self._unused_label(self._as_label(distribution) + ' sample')
return self.with_column(label, sample) | def sample_from_distribution(self, distribution, k, proportions=False) | Return a new table with the same number of rows and a new column.
The values in the distribution column are define a multinomial.
They are replaced by sample counts/proportions in the output.
>>> sizes = Table(['size', 'count']).with_rows([
... ['small', 50],
... ['medium', 100],
... ['big', 50],
... ])
>>> sizes.sample_from_distribution('count', 1000) # doctest: +SKIP
size | count | count sample
small | 50 | 239
medium | 100 | 496
big | 50 | 265
>>> sizes.sample_from_distribution('count', 1000, True) # doctest: +SKIP
size | count | count sample
small | 50 | 0.24
medium | 100 | 0.51
big | 50 | 0.25 | 4.999546 | 5.156996 | 0.969469 |
if not 1 <= k <= self.num_rows - 1:
raise ValueError("Invalid value of k. k must be between 1 and the"
"number of rows - 1")
rows = np.random.permutation(self.num_rows)
first = self.take(rows[:k])
rest = self.take(rows[k:])
for column_label in self._formats:
first._formats[column_label] = self._formats[column_label]
rest._formats[column_label] = self._formats[column_label]
return first, rest | def split(self, k) | Return a tuple of two tables where the first table contains
``k`` rows randomly sampled and the second contains the remaining rows.
Args:
``k`` (int): The number of rows randomly sampled into the first
table. ``k`` must be between 1 and ``num_rows - 1``.
Raises:
``ValueError``: ``k`` is not between 1 and ``num_rows - 1``.
Returns:
A tuple containing two instances of ``Table``.
>>> jobs = Table().with_columns(
... 'job', make_array('a', 'b', 'c', 'd'),
... 'wage', make_array(10, 20, 15, 8))
>>> jobs
job | wage
a | 10
b | 20
c | 15
d | 8
>>> sample, rest = jobs.split(3)
>>> sample # doctest: +SKIP
job | wage
c | 15
a | 10
b | 20
>>> rest # doctest: +SKIP
job | wage
d | 8 | 3.071336 | 3.308455 | 0.928329 |
self = self.copy()
self.append(row)
return self | def with_row(self, row) | Return a table with an additional row.
Args:
``row`` (sequence): A value for each column.
Raises:
``ValueError``: If the row length differs from the column count.
>>> tiles = Table(make_array('letter', 'count', 'points'))
>>> tiles.with_row(['c', 2, 3]).with_row(['d', 4, 2])
letter | count | points
c | 2 | 3
d | 4 | 2 | 5.880904 | 18.973318 | 0.309957 |
self = self.copy()
self.append(self._with_columns(zip(*rows)))
return self | def with_rows(self, rows) | Return a table with additional rows.
Args:
``rows`` (sequence of sequences): Each row has a value per column.
If ``rows`` is a 2-d array, its shape must be (_, n) for n columns.
Raises:
``ValueError``: If a row length differs from the column count.
>>> tiles = Table(make_array('letter', 'count', 'points'))
>>> tiles.with_rows(make_array(make_array('c', 2, 3),
... make_array('d', 4, 2)))
letter | count | points
c | 2 | 3
d | 4 | 2 | 8.379806 | 17.639334 | 0.475064 |
# Ensure that if with_column is called instead of with_columns;
# no error is raised.
if rest:
return self.with_columns(label, values, *rest)
new_table = self.copy()
new_table.append_column(label, values)
return new_table | def with_column(self, label, values, *rest) | Return a new table with an additional or replaced column.
Args:
``label`` (str): The column label. If an existing label is used,
the existing column will be replaced in the new table.
``values`` (single value or sequence): If a single value, every
value in the new column is ``values``. If sequence of values,
new column takes on values in ``values``.
``rest``: An alternating list of labels and values describing
additional columns. See with_columns for a full description.
Raises:
``ValueError``: If
- ``label`` is not a valid column name
- if ``label`` is not of type (str)
- ``values`` is a list/array that does not have the same
length as the number of rows in the table.
Returns:
copy of original table with new or replaced column
>>> alphabet = Table().with_column('letter', make_array('c','d'))
>>> alphabet = alphabet.with_column('count', make_array(2, 4))
>>> alphabet
letter | count
c | 2
d | 4
>>> alphabet.with_column('permutes', make_array('a', 'g'))
letter | count | permutes
c | 2 | a
d | 4 | g
>>> alphabet
letter | count
c | 2
d | 4
>>> alphabet.with_column('count', 1)
letter | count
c | 1
d | 1
>>> alphabet.with_column(1, make_array(1, 2))
Traceback (most recent call last):
...
ValueError: The column label must be a string, but a int was given
>>> alphabet.with_column('bad_col', make_array(1))
Traceback (most recent call last):
...
ValueError: Column length mismatch. New column does not have the same number of rows as table. | 4.16943 | 5.090837 | 0.819007 |
if len(labels_and_values) == 1:
labels_and_values = labels_and_values[0]
if isinstance(labels_and_values, collections.abc.Mapping):
labels_and_values = list(labels_and_values.items())
if not isinstance(labels_and_values, collections.abc.Sequence):
labels_and_values = list(labels_and_values)
if not labels_and_values:
return self
first = labels_and_values[0]
if not isinstance(first, str) and hasattr(first, '__iter__'):
for pair in labels_and_values:
assert len(pair) == 2, 'incorrect columns format'
labels_and_values = [x for pair in labels_and_values for x in pair]
assert len(labels_and_values) % 2 == 0, 'Even length sequence required'
for i in range(0, len(labels_and_values), 2):
label, values = labels_and_values[i], labels_and_values[i+1]
self = self.with_column(label, values)
return self | def with_columns(self, *labels_and_values) | Return a table with additional or replaced columns.
Args:
``labels_and_values``: An alternating list of labels and values or
a list of label-value pairs. If one of the labels is in
existing table, then every value in the corresponding column is
set to that value. If label has only a single value (``int``),
every row of corresponding column takes on that value.
Raises:
``ValueError``: If
- any label in ``labels_and_values`` is not a valid column
name, i.e if label is not of type (str).
- if any value in ``labels_and_values`` is a list/array and
does not have the same length as the number of rows in the
table.
``AssertionError``:
- 'incorrect columns format', if passed more than one sequence
(iterables) for ``labels_and_values``.
- 'even length sequence required' if missing a pair in
label-value pairs.
Returns:
Copy of original table with new or replaced columns. Columns added
in order of labels. Equivalent to ``with_column(label, value)``
when passed only one label-value pair.
>>> players = Table().with_columns('player_id',
... make_array(110234, 110235), 'wOBA', make_array(.354, .236))
>>> players
player_id | wOBA
110,234 | 0.354
110,235 | 0.236
>>> players = players.with_columns('salaries', 'N/A', 'season', 2016)
>>> players
player_id | wOBA | salaries | season
110,234 | 0.354 | N/A | 2,016
110,235 | 0.236 | N/A | 2,016
>>> salaries = Table().with_column('salary',
... make_array('$500,000', '$15,500,000'))
>>> players.with_columns('salaries', salaries.column('salary'),
... 'years', make_array(6, 1))
player_id | wOBA | salaries | season | years
110,234 | 0.354 | $500,000 | 2,016 | 6
110,235 | 0.236 | $15,500,000 | 2,016 | 1
>>> players.with_columns(2, make_array('$600,000', '$20,000,000'))
Traceback (most recent call last):
...
ValueError: The column label must be a string, but a int was given
>>> players.with_columns('salaries', make_array('$600,000'))
Traceback (most recent call last):
...
ValueError: Column length mismatch. New column does not have the same number of rows as table. | 1.921741 | 1.758785 | 1.092653 |
copy = self.copy()
copy.relabel(label, new_label)
return copy | def relabeled(self, label, new_label) | Return a new table with ``label`` specifying column label(s)
replaced by corresponding ``new_label``.
Args:
``label`` -- (str or array of str) The label(s) of
columns to be changed.
``new_label`` -- (str or array of str): The new label(s) of
columns to be changed. Same number of elements as label.
Raises:
``ValueError`` -- if ``label`` does not exist in
table, or if the ``label`` and ``new_label`` are not not of
equal length. Also, raised if ``label`` and/or ``new_label``
are not ``str``.
Returns:
New table with ``new_label`` in place of ``label``.
>>> tiles = Table().with_columns('letter', make_array('c', 'd'),
... 'count', make_array(2, 4))
>>> tiles
letter | count
c | 2
d | 4
>>> tiles.relabeled('count', 'number')
letter | number
c | 2
d | 4
>>> tiles # original table unmodified
letter | count
c | 2
d | 4
>>> tiles.relabeled(make_array('letter', 'count'),
... make_array('column1', 'column2'))
column1 | column2
c | 2
d | 4
>>> tiles.relabeled(make_array('letter', 'number'),
... make_array('column1', 'column2'))
Traceback (most recent call last):
...
ValueError: Invalid labels. Column labels must already exist in table in order to be replaced. | 3.833959 | 8.562819 | 0.447745 |
if columns:
self = self.select(*columns)
if 'normed' in vargs:
vargs.setdefault('density', vargs.pop('normed'))
density = vargs.get('density', False)
tag = 'density' if density else 'count'
cols = list(self._columns.values())
_, bins = np.histogram(cols, **vargs)
binned = type(self)().with_column('bin', bins)
for label in self.labels:
counts, _ = np.histogram(self[label], bins=bins, density=density)
binned[label + ' ' + tag] = np.append(counts, 0)
return binned | def bin(self, *columns, **vargs) | Group values by bin and compute counts per bin by column.
By default, bins are chosen to contain all values in all columns. The
following named arguments from numpy.histogram can be applied to
specialize bin widths:
If the original table has n columns, the resulting binned table has
n+1 columns, where column 0 contains the lower bound of each bin.
Args:
``columns`` (str or int): Labels or indices of columns to be
binned. If empty, all columns are binned.
``bins`` (int or sequence of scalars): If bins is an int,
it defines the number of equal-width bins in the given range
(10, by default). If bins is a sequence, it defines the bin
edges, including the rightmost edge, allowing for non-uniform
bin widths.
``range`` ((float, float)): The lower and upper range of
the bins. If not provided, range contains all values in the
table. Values outside the range are ignored.
``density`` (bool): If False, the result will contain the number of
samples in each bin. If True, the result is the value of the
probability density function at the bin, normalized such that
the integral over the range is 1. Note that the sum of the
histogram values will not be equal to 1 unless bins of unity
width are chosen; it is not a probability mass function. | 3.48646 | 4.088552 | 0.852737 |
def format_using_as_html(v, label=False):
if not label and hasattr(v, 'as_html'):
return v.as_html()
else:
return format_fn(v, label)
return format_using_as_html | def _use_html_if_available(format_fn) | Use the value's HTML rendering if available, overriding format_fn. | 3.337164 | 3.12379 | 1.068306 |
formats = {s: self._formats.get(s, self.formatter) for s in self.labels}
cols = self._columns.items()
fmts = [formats[k].format_column(k, v[:max_rows]) for k, v in cols]
if as_html:
fmts = list(map(type(self)._use_html_if_available, fmts))
return fmts | def _get_column_formatters(self, max_rows, as_html) | Return one value formatting function per column.
Each function has the signature f(value, label=False) -> str | 4.693404 | 4.652972 | 1.008689 |
if not max_rows or max_rows > self.num_rows:
max_rows = self.num_rows
omitted = max(0, self.num_rows - max_rows)
labels = self._columns.keys()
fmts = self._get_column_formatters(max_rows, False)
rows = [[fmt(label, label=True) for fmt, label in zip(fmts, labels)]]
for row in itertools.islice(self.rows, max_rows):
rows.append([f(v, label=False) for v, f in zip(row, fmts)])
lines = [sep.join(row) for row in rows]
if omitted:
lines.append('... ({} rows omitted)'.format(omitted))
return '\n'.join([line.rstrip() for line in lines]) | def as_text(self, max_rows=0, sep=" | ") | Format table as text. | 2.834067 | 2.748109 | 1.031279 |
if not max_rows or max_rows > self.num_rows:
max_rows = self.num_rows
omitted = max(0, self.num_rows - max_rows)
labels = self.labels
lines = [
(0, '<table border="1" class="dataframe">'),
(1, '<thead>'),
(2, '<tr>'),
(3, ' '.join('<th>' + label + '</th>' for label in labels)),
(2, '</tr>'),
(1, '</thead>'),
(1, '<tbody>'),
]
fmts = self._get_column_formatters(max_rows, True)
for row in itertools.islice(self.rows, max_rows):
lines += [
(2, '<tr>'),
(3, ' '.join('<td>' + fmt(v, label=False) + '</td>' for
v, fmt in zip(row, fmts))),
(2, '</tr>'),
]
lines.append((1, '</tbody>'))
lines.append((0, '</table>'))
if omitted:
lines.append((0, '<p>... ({} rows omitted)</p>'.format(omitted)))
return '\n'.join(4 * indent * ' ' + text for indent, text in lines) | def as_html(self, max_rows=0) | Format table as HTML. | 2.483723 | 2.424304 | 1.02451 |
column = self._get_column(column_or_label)
index = {}
for key, row in zip(column, self.rows):
index.setdefault(key, []).append(row)
return index | def index_by(self, column_or_label) | Return a dict keyed by values in a column that contains lists of
rows corresponding to each value. | 2.841469 | 2.553915 | 1.112593 |
dt = np.dtype(list(zip(self.labels, (c.dtype for c in self.columns))))
arr = np.empty_like(self.columns[0], dt)
for label in self.labels:
arr[label] = self[label]
return arr | def to_array(self) | Convert the table to a structured NumPy array. | 3.625938 | 3.33367 | 1.087672 |
options = self.default_options.copy()
options.update(vargs)
if column_for_xticks is not None:
x_data, y_labels = self._split_column_and_labels(column_for_xticks)
x_label = self._as_label(column_for_xticks)
else:
x_data, y_labels = None, self.labels
x_label = None
if select is not None:
y_labels = self._as_labels(select)
if x_data is not None:
self = self.sort(x_data)
x_data = np.sort(x_data)
def draw(axis, label, color):
if x_data is None:
axis.plot(self[label], color=color, **options)
else:
axis.plot(x_data, self[label], color=color, **options)
self._visualize(x_label, y_labels, None, overlay, draw, _vertical_x, width=width, height=height) | def plot(self, column_for_xticks=None, select=None, overlay=True, width=6, height=4, **vargs) | Plot line charts for the table.
Args:
column_for_xticks (``str/array``): A column containing x-axis labels
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each plot will be displayed separately.
vargs: Additional arguments that get passed into `plt.plot`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
for additional arguments that can be passed into vargs.
Raises:
ValueError -- Every selected column must be numerical.
Returns:
Returns a line plot (connected scatter). Each plot is labeled using
the values in `column_for_xticks` and one plot is produced for all
other columns in self (or for the columns designated by `select`).
>>> table = Table().with_columns(
... 'days', make_array(0, 1, 2, 3, 4, 5),
... 'price', make_array(90.5, 90.00, 83.00, 95.50, 82.00, 82.00),
... 'projection', make_array(90.75, 82.00, 82.50, 82.50, 83.00, 82.50))
>>> table
days | price | projection
0 | 90.5 | 90.75
1 | 90 | 82
2 | 83 | 82.5
3 | 95.5 | 82.5
4 | 82 | 83
5 | 82 | 82.5
>>> table.plot('days') # doctest: +SKIP
<line graph with days as x-axis and lines for price and projection>
>>> table.plot('days', overlay=False) # doctest: +SKIP
<line graph with days as x-axis and line for price>
<line graph with days as x-axis and line for projection>
>>> table.plot('days', 'price') # doctest: +SKIP
<line graph with days as x-axis and line for price> | 2.800713 | 3.08156 | 0.908862 |
options = self.default_options.copy()
# Matplotlib tries to center the labels, but we already handle that
# TODO consider changing the custom centering code and using matplotlib's default
vargs['align'] = 'edge'
options.update(vargs)
xticks, labels = self._split_column_and_labels(column_for_categories)
if select is not None:
labels = self._as_labels(select)
index = np.arange(self.num_rows)
def draw(axis, label, color):
axis.bar(index-0.5, self[label], 1.0, color=color, **options)
def annotate(axis, ticks):
if (ticks is not None) :
tick_labels = [ticks[int(l)] if 0<=l<len(ticks) else '' for l in axis.get_xticks()]
axis.set_xticklabels(tick_labels, stretch='ultra-condensed')
self._visualize(column_for_categories, labels, xticks, overlay, draw, annotate, width=width, height=height) | def bar(self, column_for_categories=None, select=None, overlay=True, width=6, height=4, **vargs) | Plot bar charts for the table.
Each plot is labeled using the values in `column_for_categories` and
one plot is produced for every other column (or for the columns
designated by `select`).
Every selected column except `column_for_categories` must be numerical.
Args:
column_for_categories (str): A column containing x-axis categories
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each will be displayed separately.
vargs: Additional arguments that get passed into `plt.bar`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
for additional arguments that can be passed into vargs. | 4.984945 | 5.183094 | 0.96177 |
self.group(column_label).bar(column_label, **vargs) | def group_bar(self, column_label, **vargs) | Plot a bar chart for the table.
The values of the specified column are grouped and counted, and one
bar is produced for each group.
Note: This differs from ``bar`` in that there is no need to specify
bar heights; the height of a category's bar is the number of copies
of that category in the given column. This method behaves more like
``hist`` in that regard, while ``bar`` behaves more like ``plot`` or
``scatter`` (which require the height of each point to be specified).
Args:
``column_label`` (str or int): The name or index of a column
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each will be displayed separately.
width (float): The width of the plot, in inches
height (float): The height of the plot, in inches
vargs: Additional arguments that get passed into `plt.bar`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
for additional arguments that can be passed into vargs. | 6.133375 | 7.809093 | 0.785415 |
options = self.default_options.copy()
# Matplotlib tries to center the labels, but we already handle that
# TODO consider changing the custom centering code and using matplotlib's default
vargs['align'] = 'edge'
options.update(vargs)
yticks, labels = self._split_column_and_labels(column_for_categories)
if select is not None:
labels = self._as_labels(select)
n = len(labels)
index = np.arange(self.num_rows)
margin = 0.1
bwidth = 1 - 2 * margin
if overlay:
bwidth /= len(labels)
if 'height' in options:
height = options.pop('height')
else:
height = max(4, len(index)/2)
def draw(axis, label, color):
if overlay:
ypos = index + margin + (1-2*margin)*(n - 1 - labels.index(label))/n
else:
ypos = index
# barh plots entries in reverse order from bottom to top
axis.barh(ypos, self[label][::-1], bwidth, color=color, **options)
ylabel = self._as_label(column_for_categories)
def annotate(axis, ticks):
axis.set_yticks(index+0.5) # Center labels on bars
# barh plots entries in reverse order from bottom to top
axis.set_yticklabels(ticks[::-1], stretch='ultra-condensed')
axis.set_xlabel(axis.get_ylabel())
axis.set_ylabel(ylabel)
self._visualize('', labels, yticks, overlay, draw, annotate, width=width, height=height) | def barh(self, column_for_categories=None, select=None, overlay=True, width=6, **vargs) | Plot horizontal bar charts for the table.
Args:
``column_for_categories`` (``str``): A column containing y-axis categories
used to create buckets for bar chart.
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each will be displayed separately.
vargs: Additional arguments that get passed into `plt.barh`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.barh
for additional arguments that can be passed into vargs.
Raises:
ValueError -- Every selected except column for ``column_for_categories``
must be numerical.
Returns:
Horizontal bar graph with buckets specified by ``column_for_categories``.
Each plot is labeled using the values in ``column_for_categories``
and one plot is produced for every other column (or for the columns
designated by ``select``).
>>> t = Table().with_columns(
... 'Furniture', make_array('chairs', 'tables', 'desks'),
... 'Count', make_array(6, 1, 2),
... 'Price', make_array(10, 20, 30)
... )
>>> t
Furniture | Count | Price
chairs | 6 | 10
tables | 1 | 20
desks | 2 | 30
>>> furniture_table.barh('Furniture') # doctest: +SKIP
<bar graph with furniture as categories and bars for count and price>
>>> furniture_table.barh('Furniture', 'Price') # doctest: +SKIP
<bar graph with furniture as categories and bars for price>
>>> furniture_table.barh('Furniture', make_array(1, 2)) # doctest: +SKIP
<bar graph with furniture as categories and bars for count and price> | 4.59147 | 4.994057 | 0.919387 |
self.group(column_label).barh(column_label, **vargs) | def group_barh(self, column_label, **vargs) | Plot a horizontal bar chart for the table.
The values of the specified column are grouped and counted, and one
bar is produced for each group.
Note: This differs from ``barh`` in that there is no need to specify
bar heights; the size of a category's bar is the number of copies
of that category in the given column. This method behaves more like
``hist`` in that regard, while ``barh`` behaves more like ``plot`` or
``scatter`` (which require the second coordinate of each point to be
specified in another column).
Args:
``column_label`` (str or int): The name or index of a column
Kwargs:
overlay (bool): create a chart with one color per data column;
if False, each will be displayed separately.
width (float): The width of the plot, in inches
height (float): The height of the plot, in inches
vargs: Additional arguments that get passed into `plt.bar`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
for additional arguments that can be passed into vargs. | 5.059006 | 7.060841 | 0.716488 |
for label in y_labels:
if not all(isinstance(x, numbers.Real) for x in self[label]):
raise ValueError("The column '{0}' contains non-numerical "
"values. A plot cannot be drawn for this column."
.format(label))
n = len(y_labels)
colors = list(itertools.islice(itertools.cycle(self.chart_colors), n))
if overlay and n > 1:
_, axis = plt.subplots(figsize=(width, height))
if x_label is not None:
axis.set_xlabel(x_label)
for label, color in zip(y_labels, colors):
draw(axis, label, color)
if ticks is not None:
annotate(axis, ticks)
axis.legend(y_labels, loc=2, bbox_to_anchor=(1.05, 1))
type(self).plots.append(axis)
else:
fig, axes = plt.subplots(n, 1, figsize=(width, height*n))
if not isinstance(axes, collections.Iterable):
axes=[axes]
for axis, y_label, color in zip(axes, y_labels, colors):
draw(axis, y_label, color)
axis.set_ylabel(y_label, fontsize=16)
if x_label is not None:
axis.set_xlabel(x_label, fontsize=16)
if ticks is not None:
annotate(axis, ticks)
type(self).plots.append(axis) | def _visualize(self, x_label, y_labels, ticks, overlay, draw, annotate, width=6, height=4) | Generic visualization that overlays or separates the draw function.
Raises:
ValueError: The Table contains non-numerical values in columns
other than `column_for_categories` | 2.328172 | 2.244328 | 1.037358 |
column = None if column_or_label is None else self._get_column(column_or_label)
labels = [label for i, label in enumerate(self.labels) if column_or_label not in (i, label)]
return column, labels | def _split_column_and_labels(self, column_or_label) | Return the specified column and labels of other columns. | 3.032828 | 2.522636 | 1.202246 |
warnings.warn("pivot_hist is deprecated; use "
"hist(value_column_label, group=pivot_column_label), or "
"with side_by_side=True if you really want side-by-side "
"bars.")
pvt_labels = np.unique(self[pivot_column_label])
pvt_columns = [self[value_column_label][np.where(self[pivot_column_label] == pivot)] for pivot in pvt_labels]
n = len(pvt_labels)
colors = list(itertools.islice(itertools.cycle(self.chart_colors), n))
if overlay:
plt.figure(figsize=(width, height))
vals, bins, patches = plt.hist(pvt_columns, color=colors, **vargs)
plt.legend(pvt_labels)
else:
_, axes = plt.subplots(n, 1, figsize=(width, height * n))
vals = []
bins = None
for axis, label, column, color in zip(axes, pvt_labels, pvt_columns, colors):
if isinstance(bins, np.ndarray):
avals, abins, patches = axis.hist(column, color=color, bins=bins, **vargs)
else:
avals, abins, patches = axis.hist(column, color=color, **vargs)
axis.set_xlabel(label, fontsize=16)
vals.append(avals)
if not isinstance(bins, np.ndarray):
bins = abins
else:
assert bins.all() == abins.all(), "Inconsistent bins in hist"
t = type(self)()
t['start'] = bins[0:-1]
t['end'] = bins[1:]
for label, column in zip(pvt_labels,vals):
t[label] = column | def pivot_hist(self, pivot_column_label, value_column_label, overlay=True, width=6, height=4, **vargs) | Draw histograms of each category in a column. | 2.681659 | 2.672596 | 1.003391 |
# Check for non-numerical values and raise a ValueError if any found
for col in self:
if any(isinstance(cell, np.flexible) for cell in self[col]):
raise ValueError("The column '{0}' contains non-numerical "
"values. A histogram cannot be drawn for this table."
.format(col))
columns = self._columns.copy()
vargs['labels'] = columns.keys()
values = list(columns.values())
plt.boxplot(values, **vargs) | def boxplot(self, **vargs) | Plots a boxplot for the table.
Every column must be numerical.
Kwargs:
vargs: Additional arguments that get passed into `plt.boxplot`.
See http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot
for additional arguments that can be passed into vargs. These include
`vert` and `showmeans`.
Returns:
None
Raises:
ValueError: The Table contains columns with non-numerical values.
>>> table = Table().with_columns(
... 'test1', make_array(92.5, 88, 72, 71, 99, 100, 95, 83, 94, 93),
... 'test2', make_array(89, 84, 74, 66, 92, 99, 88, 81, 95, 94))
>>> table
test1 | test2
92.5 | 89
88 | 84
72 | 74
71 | 66
99 | 92
100 | 99
95 | 88
83 | 81
94 | 95
93 | 94
>>> table.boxplot() # doctest: +SKIP
<boxplot of test1 and boxplot of test2 side-by-side on the same figure> | 5.039465 | 5.115924 | 0.985055 |
if arr is None:
return lambda arr: percentile(p, arr)
if hasattr(p, '__iter__'):
return np.array([percentile(x, arr) for x in p])
if p == 0:
return min(arr)
assert 0 < p <= 100, 'Percentile requires a percent'
i = (p/100) * len(arr)
return sorted(arr)[math.ceil(i) - 1] | def percentile(p, arr=None) | Returns the pth percentile of the input array (the value that is at
least as great as p% of the values in the array).
If arr is not provided, percentile returns itself curried with p
>>> percentile(74.9, [1, 3, 5, 9])
5
>>> percentile(75, [1, 3, 5, 9])
5
>>> percentile(75.1, [1, 3, 5, 9])
9
>>> f = percentile(75)
>>> f([1, 3, 5, 9])
5 | 2.901443 | 3.534684 | 0.820849 |
shade = rbound is not None or lbound is not None
shade_left = rbound is not None and lbound is not None
inf = 3.5 * sd
step = 0.1
rlabel = rbound
llabel = lbound
if rbound is None:
rbound = inf + mean
rlabel = "$\infty$"
if lbound is None:
lbound = -inf + mean
llabel = "-$\infty$"
pdf_range = np.arange(-inf + mean, inf + mean, step)
plt.plot(pdf_range, stats.norm.pdf(pdf_range, loc=mean, scale=sd), color='k', lw=1)
cdf_range = np.arange(lbound, rbound + step, step)
if shade:
plt.fill_between(cdf_range, stats.norm.pdf(cdf_range, loc=mean, scale=sd), color='gold')
if shade_left:
cdf_range = np.arange(-inf+mean, lbound + step, step)
plt.fill_between(cdf_range, stats.norm.pdf(cdf_range, loc=mean, scale=sd), color='darkblue')
plt.ylim(0, stats.norm.pdf(0, loc=0, scale=sd) * 1.25)
plt.xlabel('z')
plt.ylabel('$\phi$(z)', rotation=90)
plt.title("Normal Curve ~ ($\mu$ = {0}, $\sigma$ = {1}) "
"{2} < z < {3}".format(mean, sd, llabel, rlabel), fontsize=16)
plt.show() | def plot_normal_cdf(rbound=None, lbound=None, mean=0, sd=1) | Plots a normal curve with specified parameters and area below curve shaded
between ``lbound`` and ``rbound``.
Args:
``rbound`` (numeric): right boundary of shaded region
``lbound`` (numeric): left boundary of shaded region; by default is negative infinity
``mean`` (numeric): mean/expectation of normal distribution
``sd`` (numeric): standard deviation of normal distribution | 2.409583 | 2.552184 | 0.944126 |
proportions = sample_proportions(sample_size, table.column(label))
return table.with_column('Random Sample', proportions) | def proportions_from_distribution(table, label, sample_size,
column_name='Random Sample') | Adds a column named ``column_name`` containing the proportions of a random
draw using the distribution in ``label``.
This method uses ``np.random.multinomial`` to draw ``sample_size`` samples
from the distribution in ``table.column(label)``, then divides by
``sample_size`` to create the resulting column of proportions.
Args:
``table``: An instance of ``Table``.
``label``: Label of column in ``table``. This column must contain a
distribution (the values must sum to 1).
``sample_size``: The size of the sample to draw from the distribution.
``column_name``: The name of the new column that contains the sampled
proportions. Defaults to ``'Random Sample'``.
Returns:
A copy of ``table`` with a column ``column_name`` containing the
sampled proportions. The proportions will sum to 1.
Throws:
``ValueError``: If the ``label`` is not in the table, or if
``table.column(label)`` does not sum to 1. | 4.342202 | 6.536663 | 0.664284 |
from . import Table
df = table.to_df()
if subset is not None:
# Iterate through columns
subset = np.atleast_1d(subset)
if any([i not in df.columns for i in subset]):
err = np.where([i not in df.columns for i in subset])[0]
err = "Column mismatch: {0}".format(
[subset[i] for i in err])
raise ValueError(err)
for col in subset:
df[col] = df[col].apply(func)
else:
df = df.apply(func)
if isinstance(df, pd.Series):
# Reshape it so that we can easily convert back
df = pd.DataFrame(df).T
tab = Table.from_df(df)
return tab | def table_apply(table, func, subset=None) | Applies a function to each column and returns a Table.
Uses pandas `apply` under the hood, then converts back to a Table
Args:
table : instance of Table
The table to apply your function to
func : function
Any function that will work with DataFrame.apply
subset : list | None
A list of columns to apply the function to. If None, function
will be applied to all columns in table
Returns
-------
tab : instance of Table
A table with the given function applied. It will either be the
shape == shape(table), or shape (1, table.shape[1]) | 3.032962 | 3.109543 | 0.975372 |
if start is None:
assert not array, "Please pass starting values explicitly when array=True"
arg_count = f.__code__.co_argcount
assert arg_count > 0, "Please pass starting values explicitly for variadic functions"
start = [0] * arg_count
if not hasattr(start, '__len__'):
start = [start]
if array:
objective = f
else:
@functools.wraps(f)
def objective(args):
return f(*args)
if not smooth and 'method' not in vargs:
vargs['method'] = 'Powell'
result = optimize.minimize(objective, start, **vargs)
if log is not None:
log(result)
if len(start) == 1:
return result.x.item(0)
else:
return result.x | def minimize(f, start=None, smooth=False, log=None, array=False, **vargs) | Minimize a function f of one or more arguments.
Args:
f: A function that takes numbers and returns a number
start: A starting value or list of starting values
smooth: Whether to assume that f is smooth and use first-order info
log: Logging function called on the result of optimization (e.g. print)
vargs: Other named arguments passed to scipy.optimize.minimize
Returns either:
(a) the minimizing argument of a one-argument function
(b) an array of minimizing arguments of a multi-argument function | 2.932294 | 2.986574 | 0.981825 |
if len(s) >= 2 and isinstance(s[0], _number) and isinstance(s[0], _number):
lat, lon = s[1], s[0]
return [(lat, lon)]
else:
return [lat_lon for sub in s for lat_lon in _lat_lons_from_geojson(sub)] | def _lat_lons_from_geojson(s) | Return a latitude-longitude pairs from nested GeoJSON coordinates.
GeoJSON coordinates are always stored in (longitude, latitude) order. | 2.989637 | 2.903578 | 1.029639 |
if not self._folium_map:
self.draw()
return self._inline_map(self._folium_map, self._width, self._height) | def as_html(self) | Generate HTML to display map. | 6.831757 | 4.833715 | 1.413355 |
IPython.display.display(IPython.display.HTML(self.as_html())) | def show(self) | Publish HTML. | 6.111886 | 4.454967 | 1.371926 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.