pandas-8分层和多级索引

pandas -8 分层和多级索引

Multi-level indexing. 在 “pandas -2 索引和选择数据” 一节中, 已经提到了如何选择行列元素, 而Series 和 Dataframe 是低维度的数据结构,对于更高维度的数据,可以通过分层和多级索引来实现。

分层索引的创建

创建分层索引的方式有很多, 这里直接摘抄自官方的文档,可以通过元组,列表,Dataframe, arrays 等方式生成分层索引。

同时要知道,通过 groupby 分组操作之后得到的也是这种分层结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    //  1. 元组
In:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo','qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
Out:
[('bar', 'one'),
('bar', 'two'),
('baz', 'one'),
('baz', 'two'),
('foo', 'one'),
('foo', 'two'),
('qux', 'one'),
('qux', 'two')]

In:
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.Series(np.random.randn(8), index=index)

Out:
first second
bar one 0.469112
two -0.282863
baz one -1.509059
two -1.135632
foo one 1.212112
two -0.173215
qux one 0.119209
two -1.044236
dtype: float64


// 2. dataftame

index = pd.MultiIndex.from_frame(df)


// 3. arrays

In:
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]


s = pd.Series(np.random.randn(8), index=arrays)

从DataFrame 产生 MultiIndex

1
df = df.set_index(['col1','col2'])

MultiIndex 转化成 列

1
df = df.reset_index()

选择不同层

查看不同层的索引值。

1
2
3
4
5
6
7
In:
index.get_level_values(0)

index.get_level_values("name")

Out:
Index(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], dtype='object', name='first')

根据不同层索引

1
2
3
4
5
6
df["bar"]
df["one"]
df["bar"]["one"]

// 元组
df.loc[('bar', 'two')]
注意, 切片时不会改变 多层索引。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值