Pandas数据处理之Pandas的Index对象

《Python数据科学手册》读书笔记

3.2.3 Pandas的Index对象

  Series 和DataFrame 对象都使用便于引用和调整的显式索引。。Pandas 的
Index 对象是一个很有趣的数据结构,可以将它看作是一个不可变数组或有序集合

In [1] : import numpy as np
		 import pandas as pd			
In [2] : ind = pd.Index([2,3,5,7,11])
In [3] : ind 
Out[3] :Int64Index([2, 3, 5, 7, 11], dtype='int64')

1. 将Index看作不可变数组

  Index 对象的许多操作都像数组。例如,可以通过标准Python 的取值方法获取数值,也可以通过切片获取数值:

In [4] : ind[1]
Out[4] :3

In [5] : ind[::2]
Out[5] :Int64Index([2, 5, 11], dtype='int64')

# 类似于Numpy的属性
In [6] : ind.size
Out[6] :5
In [6] : ind.shape
Out[6] :(5,)
In [6] : ind.dtype
Out[6] :dtype('int64')

  Index 对象与NumPy 数组之间的不同在于,Index 对象的索引是不可变的,也就是说不能通过通常的方式进行调整:

In [7] : ind[1] = 0
TypeError: Index does not support mutable operations

  Index 对象的不可变特征使得多个DataFrame 和数组之间进行索引共享时更加安全,尤其是可以避免因修改索引时粗心大意而导致的副作用。

2. 将Index看作有序集合

Index对象可以求交集、并集

In [8] : indA = pd.Index([1, 3, 5, 7, 9])
		 indB = pd.Index([2, 3, 5, 7, 11])
		 
In [9] : indA & indB 	# 交集
Out[9] : Int64Index([3, 5, 7], dtype='int64')

In[10] : indA | indB 	# 并集
Out[10]: Int64Index([1, 2, 3, 5, 7, 9, 11], dtype='int64')

In[11] : indA ^ indB # 异或
Out[11]: Int64Index([1, 2, 9, 11], dtype='int64')
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值