本文整理汇总了Python中pandas.MultiIndex.from_product方法的典型用法代码示例。如果您正苦于以下问题:Python MultiIndex.from_product方法的具体用法?Python MultiIndex.from_product怎么用?Python MultiIndex.from_product使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandas.MultiIndex
的用法示例。
在下文中一共展示了MultiIndex.from_product方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_labels_dtypes
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_labels_dtypes():
# GH 8456
i = MultiIndex.from_tuples([('A', 1), ('A', 2)])
assert i.codes[0].dtype == 'int8'
assert i.codes[1].dtype == 'int8'
i = MultiIndex.from_product([['a'], range(40)])
assert i.codes[1].dtype == 'int8'
i = MultiIndex.from_product([['a'], range(400)])
assert i.codes[1].dtype == 'int16'
i = MultiIndex.from_product([['a'], range(40000)])
assert i.codes[1].dtype == 'int32'
i = pd.MultiIndex.from_product([['a'], range(1000)])
assert (i.codes[0] >= 0).all()
assert (i.codes[1] >= 0).all()
示例2: take_invalid_kwargs
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def take_invalid_kwargs():
vals = [['A', 'B'],
[pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')]]
idx = pd.MultiIndex.from_product(vals, names=['str', 'dt'])
indices = [1, 2]
msg = r"take\(\) got an unexpected keyword argument 'foo'"
with pytest.raises(TypeError, match=msg):
idx.take(indices, foo=2)
msg = "the 'out' parameter is not supported"
with pytest.raises(ValueError, match=msg):
idx.take(indices, out=indices)
msg = "the 'mode' parameter is not supported"
with pytest.raises(ValueError, match=msg):
idx.take(indices, mode='clip')
示例3: test_large_multiindex_error
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_large_multiindex_error():
# GH12527
df_below_1000000 = pd.DataFrame(
1, index=pd.MultiIndex.from_product([[1, 2], range(499999)]),
columns=['dest'])
with pytest.raises(KeyError):
df_below_1000000.loc[(-1, 0), 'dest']
with pytest.raises(KeyError):
df_below_1000000.loc[(3, 0), 'dest']
df_above_1000000 = pd.DataFrame(
1, index=pd.MultiIndex.from_product([[1, 2], range(500001)]),
columns=['dest'])
with pytest.raises(KeyError):
df_above_1000000.loc[(-1, 0), 'dest']
with pytest.raises(KeyError):
df_above_1000000.loc[(3, 0), 'dest']
示例4: test_from_product_iterator
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_from_product_iterator():
# GH 18434
first = ['foo', 'bar', 'buz']
second = ['a', 'b', 'c']
names = ['first', 'second']
tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'), ('bar', 'a'),
('bar', 'b'), ('bar', 'c'), ('buz', 'a'), ('buz', 'b'),
('buz', 'c')]
expected = MultiIndex.from_tuples(tuples, names=names)
# iterator as input
result = MultiIndex.from_product(iter([first, second]), names=names)
tm.assert_index_equal(result, expected)
# Invalid non-iterable input
msg = "Input must be a list / sequence of iterables."
with pytest.raises(TypeError, match=msg):
MultiIndex.from_product(0)
示例5: test_getitem_partial_int
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_getitem_partial_int(self):
# GH 12416
# with single item
l1 = [10, 20]
l2 = ['a', 'b']
df = DataFrame(index=range(2),
columns=MultiIndex.from_product([l1, l2]))
expected = DataFrame(index=range(2),
columns=l2)
result = df[20]
tm.assert_frame_equal(result, expected)
# with list
expected = DataFrame(index=range(2),
columns=MultiIndex.from_product([l1[1:], l2]))
result = df[[20]]
tm.assert_frame_equal(result, expected)
# missing item:
with pytest.raises(KeyError, match='1'):
df[1]
with pytest.raises(KeyError, match=r"'\[1\] not in index'"):
df[[1]]
示例6: test_loc_multiindex_indexer_none
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_loc_multiindex_indexer_none(self):
# GH6788
# multi-index indexer is None (meaning take all)
attributes = ['Attribute' + str(i) for i in range(1)]
attribute_values = ['Value' + str(i) for i in range(5)]
index = MultiIndex.from_product([attributes, attribute_values])
df = 0.1 * np.random.randn(10, 1 * 5) + 0.5
df = DataFrame(df, columns=index)
result = df[attributes]
tm.assert_frame_equal(result, df)
# GH 7349
# loc with a multi-index seems to be doing fallback
df = DataFrame(np.arange(12).reshape(-1, 1),
index=MultiIndex.from_product([[1, 2, 3, 4],
[1, 2, 3]]))
expected = df.loc[([1, 2], ), :]
result = df.loc[[1, 2]]
tm.assert_frame_equal(result, expected)
示例7: test_multiindex_contains_dropped
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_multiindex_contains_dropped(self):
# GH 19027
# test that dropped MultiIndex levels are not in the MultiIndex
# despite continuing to be in the MultiIndex's levels
idx = MultiIndex.from_product([[1, 2], [3, 4]])
assert 2 in idx
idx = idx.drop(2)
# drop implementation keeps 2 in the levels
assert 2 in idx.levels[0]
# but it should no longer be in the index itself
assert 2 not in idx
# also applies to strings
idx = MultiIndex.from_product([['a', 'b'], ['c', 'd']])
assert 'a' in idx
idx = idx.drop('a')
assert 'a' in idx.levels[0]
assert 'a' not in idx
示例8: test_rename_axis_mapper
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_rename_axis_mapper(self):
# GH 19978
mi = MultiIndex.from_product([['a', 'b', 'c'], [1, 2]],
names=['ll', 'nn'])
s = Series([i for i in range(len(mi))], index=mi)
result = s.rename_axis(index={'ll': 'foo'})
assert result.index.names == ['foo', 'nn']
result = s.rename_axis(index=str.upper, axis=0)
assert result.index.names == ['LL', 'NN']
result = s.rename_axis(index=['foo', 'goo'])
assert result.index.names == ['foo', 'goo']
with pytest.raises(TypeError, match='unexpected'):
s.rename_axis(columns='wrong')
示例9: test_cat_on_filtered_index
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_cat_on_filtered_index(self):
df = DataFrame(index=MultiIndex.from_product(
[[2011, 2012], [1, 2, 3]], names=['year', 'month']))
df = df.reset_index()
df = df[df.month > 1]
str_year = df.year.astype('str')
str_month = df.month.astype('str')
str_both = str_year.str.cat(str_month, sep=' ')
assert str_both.loc[1] == '2011 2'
str_multiple = str_year.str.cat([str_month, str_month], sep=' ')
assert str_multiple.loc[1] == '2011 2 2'
示例10: test_delitem_multiindex
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_delitem_multiindex(self):
midx = MultiIndex.from_product([['A', 'B'], [1, 2]])
df = DataFrame(np.random.randn(4, 4), columns=midx)
assert len(df.columns) == 4
assert ('A', ) in df.columns
assert 'A' in df.columns
result = df['A']
assert isinstance(result, DataFrame)
del df['A']
assert len(df.columns) == 2
# A still in the levels, BUT get a KeyError if trying
# to delete
assert ('A', ) not in df.columns
with pytest.raises(KeyError):
del df[('A',)]
# behavior of dropped/deleted MultiIndex levels changed from
# GH 2770 to GH 19027: MultiIndex no longer '.__contains__'
# levels which are dropped/deleted
assert 'A' not in df.columns
with pytest.raises(KeyError):
del df['A']
示例11: test_cat_on_filtered_index
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_cat_on_filtered_index(self):
df = DataFrame(index=MultiIndex.from_product(
[[2011, 2012], [1, 2, 3]], names=['year', 'month']))
df = df.reset_index()
df = df[df.month > 1]
str_year = df.year.astype('str')
str_month = df.month.astype('str')
str_both = str_year.str.cat(str_month, sep=' ', join='left')
assert str_both.loc[1] == '2011 2'
str_multiple = str_year.str.cat([str_month, str_month],
sep=' ', join='left')
assert str_multiple.loc[1] == '2011 2 2'
示例12: test_repeat
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_repeat():
reps = 2
numbers = [1, 2, 3]
names = np.array(['foo', 'bar'])
m = MultiIndex.from_product([
numbers, names], names=names)
expected = MultiIndex.from_product([
numbers, names.repeat(reps)], names=names)
tm.assert_index_equal(m.repeat(reps), expected)
示例13: test_repr_roundtrip
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_repr_roundtrip():
mi = MultiIndex.from_product([list('ab'), range(3)],
names=['first', 'second'])
str(mi)
if PY3:
tm.assert_index_equal(eval(repr(mi)), mi, exact=True)
else:
result = eval(repr(mi))
# string coerces to unicode
tm.assert_index_equal(result, mi, exact=False)
assert mi.get_level_values('first').inferred_type == 'string'
assert result.get_level_values('first').inferred_type == 'unicode'
mi_u = MultiIndex.from_product(
[list(u'ab'), range(3)], names=['first', 'second'])
result = eval(repr(mi_u))
tm.assert_index_equal(result, mi_u, exact=True)
# formatting
if PY3:
str(mi)
else:
compat.text_type(mi)
# long format
mi = MultiIndex.from_product([list('abcdefg'), range(10)],
names=['first', 'second'])
if PY3:
tm.assert_index_equal(eval(repr(mi)), mi, exact=True)
else:
result = eval(repr(mi))
# string coerces to unicode
tm.assert_index_equal(result, mi, exact=False)
assert mi.get_level_values('first').inferred_type == 'string'
assert result.get_level_values('first').inferred_type == 'unicode'
result = eval(repr(mi_u))
tm.assert_index_equal(result, mi_u, exact=True)
示例14: test_roundtrip_pickle_with_tz
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_roundtrip_pickle_with_tz():
return
# GH 8367
# round-trip of timezone
index = MultiIndex.from_product(
[[1, 2], ['a', 'b'], date_range('20130101', periods=3,
tz='US/Eastern')
], names=['one', 'two', 'three'])
unpickled = tm.round_trip_pickle(index)
assert index.equal_levels(unpickled)
示例15: test_contains_top_level
# 需要导入模块: from pandas import MultiIndex [as 别名]
# 或者: from pandas.MultiIndex import from_product [as 别名]
def test_contains_top_level():
midx = MultiIndex.from_product([['A', 'B'], [1, 2]])
assert 'A' in midx
assert 'A' not in midx._engine