pandas--带有重复值的轴索引

本文介绍了在Pandas中处理带有重复索引的数据,包括Series和DataFrame的实例。展示了如何创建这些数据结构,并演示了针对重复索引进行数据选择的不同行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前的所有范例都有着唯一的轴标签(索引值)。
下面就看看带有重复索引值的Series
 1 obj=Series(range(5),index=['a','a','b','b','c'])
 2 
 3 obj
 4 Out[33]: 
 5 a    0
 6 a    1
 7 b    2
 8 b    3
 9 c    4
10 dtype: int64

索引的is_unique属性可以告诉你它的值是否是唯一的:

obj.index.is_unique
Out[34]: False

对带有重复值的索引,选取数据时,如果某个索引对应多个值,则返回一个Series;而对应单个值的,则返回一个标量值。

 1 obj['a']
 2 Out[35]: 
 3 a    0
 4 a    1
 5 dtype: int64
 6 
 7 obj['b']
 8 Out[36]: 
 9 b    2
10 b    3
11 dtype: int64

DataFrame的行索引也是如此:

 1 df=DataFrame(np.random.randn(4,3),index=['a','a','b','b'])
 2 
 3 df
 4 Out[39]: 
 5           0         1         2
 6 a -0.661187 -0.624006  0.073817
 7 a -1.460339  0.705815  1.282448
 8 b  1.759900 -0.149222  0.648127
 9 b -1.236652  0.125667 -0.144872
10 
11 df.ix['b']
12 __main__:1: DeprecationWarning: 
13 .ix is deprecated. Please use
14 .loc for label based indexing or
15 .iloc for positional indexing
16 
17 See the documentation here:
18 http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
19 Out[40]: 
20           0         1         2
21 b  1.759900 -0.149222  0.648127
22 b -1.236652  0.125667 -0.144872

 

转载于:https://www.cnblogs.com/dataAnalysis/p/9329674.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值