Pandas数据操作与索引:全面指南
1. 索引的不可变性与有序集合特性
在Pandas中,索引不支持可变操作,这种不可变性使得在多个DataFrame和数组之间共享索引更加安全,避免了因意外修改索引而产生的副作用。
同时,Pandas的Index对象遵循Python内置集合数据结构的许多约定,可以像操作集合一样进行并集、交集、差集等运算。例如:
import pandas as pd
indA = pd.Index([1, 3, 5, 7, 9])
indB = pd.Index([2, 3, 5, 7, 11])
# 交集
print(indA & indB) # Int64Index([3, 5, 7], dtype='int64')
# 并集
print(indA | indB) # Int64Index([1, 2, 3, 5, 7, 9, 11], dtype='int64')
# 对称差集
print(indA ^ indB) # Int64Index([1, 2, 9, 11], dtype='int64')
这些操作也可以通过对象方法来实现,如 indA.intersection(indB) 。
2. 数据索引与选择
在NumPy中,我们可以通过索引、切片、掩码、花式索引等方式访问和修改数组中的值。在Pandas的Series和DataFrame对象中,也有类似的操作方式,但有一些需要注意的地方。
超级会员免费看
订阅专栏 解锁全文
1709

被折叠的 条评论
为什么被折叠?



