pandas新手入门教程十

接上文。
今天玩点高端的东西:多级索引。
这东西稍微有点复杂,我们先来看看最终的样子是酱婶的:


多级索引

今天的df和之前的比,就是在索引部分不再是一层。
我们慢慢的开始

第一步,创建索引

index_tuples = list(zip(['bar', 'bar', 'baz', 'baz',
                        'foo', 'foo', 'qux', 'qux'],
                      ['one', 'two', 'one', 'two',
                         'one', 'two', 'one', 'two']))
index_tuples

内容如下:


index_tuples

就是这样特殊的的list,里面包裹的tuple,每个tuple的第一个元素是一级索引,第二个元素是二级索引。


index_tuples

因为索引是多级的,所以使用pd.MultiIndex.from_tuples来构建。

row_index = pd.MultiIndex.from_tuples(index_tuples, names=['row_first', 'row_second'])
row_index

index_tuples刚才构建的index,names为可选项,可以通过它设置你的索引名称。


row_index

第二步 构建DataFrame

df = pd.DataFrame(np.random.randn(8, 2), index=row_index, columns=['A', 'B'])
df

index参数指定使用刚才构建的多级索引

df

再复杂一点

这样一个多级索引的DataFrame就构建完了。
那现在我们再复杂一点,在column上也指定多级索引,尝试用刚才的套路进行。

col_tuples = list(zip(['X', 'X', 'Y'],
                      ['one', 'two', 'one']))
col_index = pd.MultiIndex.from_tuples(col_tuples, names=['col_first', 'col_second'])
df1 = pd.DataFrame(np.random.randn(8, 3), index=row_index, columns=col_index)
df1

输出:


多级索引

多级索引的操作

我们仅以loc操作为例子:

df1.loc[("bar")]
输出一级行索引bar行

我想更精准一点,指定二级索引怎么办?

df1.loc[("bar", "two")]
通过两级行索引来选取元素

再精准一点,选取特定的行加特定的列呢?

df1.loc[("bar", "two"), (["X","Y"], "one")]
image.png

第一个tuple("bar", "two")代表行
第二个tuple (["X","Y"], "one")代表列
其中的["X","Y"]列的第一级索引,"one"二级索引

你可能感兴趣的:(pandas新手入门教程十)