本文整理匯總了Python中pandas.core.index.MultiIndex方法的典型用法代碼示例。如果您正苦於以下問題:Python index.MultiIndex方法的具體用法?Python index.MultiIndex怎麽用?Python index.MultiIndex使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pandas.core.index
的用法示例。
在下文中一共展示了index.MultiIndex方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: var
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def var(self, ddof=1, *args, **kwargs):
"""
Compute variance of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
Parameters
----------
ddof : integer, default 1
degrees of freedom
"""
nv.validate_groupby_func('var', args, kwargs)
if ddof == 1:
try:
return self._cython_agg_general('var', **kwargs)
except Exception:
f = lambda x: x.var(ddof=ddof, **kwargs)
with _group_selection_context(self):
return self._python_agg_general(f)
else:
f = lambda x: x.var(ddof=ddof, **kwargs)
with _group_selection_context(self):
return self._python_agg_general(f)
示例2: test_reorder_levels
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def test_reorder_levels(self):
index = MultiIndex(levels=[['bar'], ['one', 'two', 'three'], [0, 1]],
labels=[[0, 0, 0, 0, 0, 0], [0, 1, 2, 0, 1, 2],
[0, 1, 0, 1, 0, 1]],
names=['L0', 'L1', 'L2'])
s = Series(np.arange(6), index=index)
# no change, position
result = s.reorder_levels([0, 1, 2])
assert_series_equal(s, result)
# no change, labels
result = s.reorder_levels(['L0', 'L1', 'L2'])
assert_series_equal(s, result)
# rotate, position
result = s.reorder_levels([1, 2, 0])
e_idx = MultiIndex(levels=[['one', 'two', 'three'], [0, 1], ['bar']],
labels=[[0, 1, 2, 0, 1, 2], [0, 1, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0]],
names=['L1', 'L2', 'L0'])
expected = Series(np.arange(6), index=e_idx)
assert_series_equal(result, expected)
示例3: _multi_take_opportunity
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _multi_take_opportunity(self, tup):
from pandas.core.generic import NDFrame
# ugly hack for GH #836
if not isinstance(self.obj, NDFrame):
return False
if not all(is_list_like_indexer(x) for x in tup):
return False
# just too complicated
for indexer, ax in zip(tup, self.obj._data.axes):
if isinstance(ax, MultiIndex):
return False
elif com.is_bool_indexer(indexer):
return False
elif not ax.is_unique:
return False
return True
示例4: _is_scalar_access
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _is_scalar_access(self, key):
# this is a shortcut accessor to both .loc and .iloc
# that provide the equivalent access of .at and .iat
# a) avoid getting things via sections and (to minimize dtype changes)
# b) provide a performant path
if not hasattr(key, '__len__'):
return False
if len(key) != self.ndim:
return False
for i, k in enumerate(key):
if not is_scalar(k):
return False
ax = self.obj.axes[i]
if isinstance(ax, MultiIndex):
return False
if not ax.is_unique:
return False
return True
示例5: _get_partial_string_timestamp_match_key
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _get_partial_string_timestamp_match_key(self, key, labels):
"""Translate any partial string timestamp matches in key, returning the
new key (GH 10331)"""
if isinstance(labels, MultiIndex):
if isinstance(key, compat.string_types) and \
labels.levels[0].is_all_dates:
# Convert key '2016-01-01' to
# ('2016-01-01'[, slice(None, None, None)]+)
key = tuple([key] + [slice(None)] * (len(labels.levels) - 1))
if isinstance(key, tuple):
# Convert (..., '2016-01-01', ...) in tuple to
# (..., slice('2016-01-01', '2016-01-01', None), ...)
new_key = []
for i, component in enumerate(key):
if isinstance(component, compat.string_types) and \
labels.levels[i].is_all_dates:
new_key.append(slice(component, component, None))
else:
new_key.append(component)
key = tuple(new_key)
return key
示例6: _write_body
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _write_body(self, indent):
self.write('<tbody>', indent)
indent += self.indent_delta
fmt_values = {}
for i in range(min(len(self.columns), self.max_cols)):
fmt_values[i] = self.fmt._format_col(i)
# write values
if self.fmt.index:
if isinstance(self.frame.index, MultiIndex):
self._write_hierarchical_rows(fmt_values, indent)
else:
self._write_regular_rows(fmt_values, indent)
else:
for i in range(min(len(self.frame), self.max_rows)):
row = [fmt_values[j][i] for j in range(len(self.columns))]
self.write_tr(row, indent, self.indent_delta, tags=None)
indent -= self.indent_delta
self.write('</tbody>', indent)
indent -= self.indent_delta
return indent
示例7: __setitem__
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def __setitem__(self, key, value):
# kludgetastic
ax = self.obj._get_axis(0)
if isinstance(ax, MultiIndex):
try:
indexer = ax.get_loc(key)
self._setitem_with_indexer(indexer, value)
return
except Exception:
pass
if isinstance(key, tuple):
if len(key) > self.ndim:
raise IndexingError('only tuples of length <= %d supported' %
self.ndim)
indexer = self._convert_tuple(key, is_setter=True)
else:
indexer = self._convert_to_indexer(key, is_setter=True)
self._setitem_with_indexer(indexer, value)
示例8: _multi_take_opportunity
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _multi_take_opportunity(self, tup):
from pandas.core.generic import NDFrame
# ugly hack for GH #836
if not isinstance(self.obj, NDFrame):
return False
if not all(_is_list_like(x) for x in tup):
return False
# just too complicated
for indexer, ax in zip(tup, self.obj._data.axes):
if isinstance(ax, MultiIndex):
return False
elif com._is_bool_indexer(indexer):
return False
return True
示例9: _write_body
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _write_body(self, indent):
self.write('<tbody>', indent)
indent += self.indent_delta
fmt_values = {}
for i in range(min(len(self.columns), self.max_cols)):
fmt_values[i] = self.fmt._format_col(i)
truncated = (len(self.columns) > self.max_cols)
# write values
if self.fmt.index:
if isinstance(self.frame.index, MultiIndex):
self._write_hierarchical_rows(fmt_values, indent)
else:
self._write_regular_rows(fmt_values, indent, truncated)
else:
for i in range(len(self.frame)):
row = [fmt_values[j][i] for j in range(len(self.columns))]
self.write_tr(row, indent, self.indent_delta, tags=None)
indent -= self.indent_delta
self.write('</tbody>', indent)
indent -= self.indent_delta
return indent
示例10: _format_header_regular
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _format_header_regular(self):
has_aliases = isinstance(self.header, (tuple, list, np.ndarray))
if has_aliases or self.header:
coloffset = 0
if self.index:
coloffset = 1
if isinstance(self.df.index, MultiIndex):
coloffset = len(self.df.index[0])
colnames = self.columns
if has_aliases:
if len(self.header) != len(self.columns):
raise ValueError(('Writing %d cols but got %d aliases'
% (len(self.columns), len(self.header))))
else:
colnames = self.header
for colindex, colname in enumerate(colnames):
yield ExcelCell(self.rowcounter, colindex + coloffset, colname,
header_style)
示例11: _multi_take_opportunity
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def _multi_take_opportunity(self, tup):
from pandas.core.generic import NDFrame
# ugly hack for GH #836
if not isinstance(self.obj, NDFrame):
return False
if not all(is_list_like_indexer(x) for x in tup):
return False
# just too complicated
for indexer, ax in zip(tup, self.obj._data.axes):
if isinstance(ax, MultiIndex):
return False
elif is_bool_indexer(indexer):
return False
elif not ax.is_unique:
return False
return True
示例12: test_multilevel_name_print
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def test_multilevel_name_print(self):
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two',
'three']],
codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
names=['first', 'second'])
s = Series(lrange(0, len(index)), index=index, name='sth')
expected = ["first second", "foo one 0",
" two 1", " three 2",
"bar one 3", " two 4",
"baz two 5", " three 6",
"qux one 7", " two 8",
" three 9", "Name: sth, dtype: int64"]
expected = "\n".join(expected)
assert repr(s) == expected
示例13: stack_sparse_frame
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def stack_sparse_frame(frame):
"""
Only makes sense when fill_value is NaN
"""
lengths = [s.sp_index.npoints for _, s in compat.iteritems(frame)]
nobs = sum(lengths)
# this is pretty fast
minor_codes = np.repeat(np.arange(len(frame.columns)), lengths)
inds_to_concat = []
vals_to_concat = []
# TODO: Figure out whether this can be reached.
# I think this currently can't be reached because you can't build a
# SparseDataFrame with a non-np.NaN fill value (fails earlier).
for _, series in compat.iteritems(frame):
if not np.isnan(series.fill_value):
raise TypeError('This routine assumes NaN fill value')
int_index = series.sp_index.to_int_index()
inds_to_concat.append(int_index.indices)
vals_to_concat.append(series.sp_values)
major_codes = np.concatenate(inds_to_concat)
stacked_values = np.concatenate(vals_to_concat)
index = MultiIndex(levels=[frame.index, frame.columns],
codes=[major_codes, minor_codes],
verify_integrity=False)
lp = DataFrame(stacked_values.reshape((nobs, 1)), index=index,
columns=['foo'])
return lp.sort_index(level=0)
示例14: result_index
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def result_index(self):
if not self.compressed and len(self.groupings) == 1:
return self.groupings[0].result_index.rename(self.names[0])
codes = self.recons_labels
levels = [ping.result_index for ping in self.groupings]
result = MultiIndex(levels=levels,
codes=codes,
verify_integrity=False,
names=self.names)
return result
示例15: std
# 需要導入模塊: from pandas.core import index [as 別名]
# 或者: from pandas.core.index import MultiIndex [as 別名]
def std(self, ddof=1, *args, **kwargs):
"""
Compute standard deviation of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
Parameters
----------
ddof : integer, default 1
degrees of freedom
"""
# TODO: implement at Cython level?
nv.validate_groupby_func('std', args, kwargs)
return np.sqrt(self.var(ddof=ddof, **kwargs))