使用 MultiIndex 创建示例 DataFrame
import pandas as pd
import numpy as np
Using from_tuples
:
np.random.seed(0)
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
idx = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
Using from_product
:
idx = pd.MultiIndex.from_product([['bar', 'baz', 'foo', 'qux'],['one','two']])
然后,使用此 MultiIndex:
df = pd.DataFrame(np.random.randn(8, 2), index=idx, columns=['A', 'B'])
print (df)
A B
first second
bar one 1.764052 0.400157
two 0.978738 2.240893
baz one 1.867558 -0.977278
two 0.950088 -0.151357
foo one -0.103219 0.410599
two 0.144044 1.454274
qux one 0.761038 0.121675
two 0.443863 0.333674