Pandas索引操作:行索引、列索引、索引的分类、重复索引的处理。
# Series索引
s = pd.Series(np.random.rand(5), index=list('abcde'))
s
s.index # 行索引
s.index.name = 'haha' # 给行索引起名字
s
# DataFrame索引
df = pd.DataFrame(np.random.randn(4, 3), columns=['one', 'two', 'three'])
df
df.index # 行索引
df.columns # 列索引
df.index.name = 'row' # 给行索引起名字
df.columns.name = 'col' # 给列索引起名字
df
# 查询pandas内置索引的类
pd.*Index?
# 重复索引(索引中含有重复项)
s = pd.Series(np.random.rand(6), index=list('abcbda')) # 索引‘a’,'b'重复出现
s
s['a'] # 查询重复索引,返回一个数组
s.index.is_unique # 判断是否含有重复索引
s.index.unique() # 返回不含重复项的索引
# 重复索引处理
s.groupby(s.index).sum() # 对于重复索引求和
s.groupby(s.index).mean() # 对于重复索引求平均值
s.groupby(s.index).first() # 对于重复索引取第一项
# ...
# 层次化索引(可以用二维数组表示更高维度的数组:pd.MultiIndex)
# Series 多层索引
a = [['a', 'a', 'a', 'b', 'b', 'c', 'c'], [1, 2, 3, 1, 2, 2, 3]]
tuples = list(zip(*a)) # 单层索引是单个元素,可以把多层索引理解为元组
tuples
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) # 第一层索引起名‘first’,第二层索引起名为‘second’
index
s = pd.Series(np.random.randn(7), index=index)
s
s.index
s.index.levels[0]
# # DataFrame多层索引
df = pd.DataFrame(np.random.randint(1, 10, (4, 3)),
index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
columns=[['one', 'one', 'two'], ['blue', 'red', 'blue']])
df.index.names = ['row-1', 'row-2']
df.columns.names = ['col-1', 'col-2']
df
df.loc['a']
type(df.loc['a'])
df.loc['a', 1]
df.loc['a', 1].index
# 索引的交换
df2 = df.swaplevel('row-1', 'row-2') # 一级索引和二级索引交换
df2
# 索引的排序
df2.sort_index(0) # 根据一级索引排序
df2.sort_index(1) # 根据二级索引排序
# 多级索引统计
df2.sum(level=0) # 根据一级索引,后面数据都进行求和操作
df2.sum(level=1) # 根据二级索引,后面数据都进行求和操作
# 索引与列的转换
df = pd.DataFrame({
'a': range(7),
'b': range(7, 0, -1),
'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'],
'd': [0, 1, 2, 0, 1, 2, 3]
})
df
df.set_index('c') # 把‘c’列设置为索引
df2 = df.set_index(['c', 'd']) #把‘c’和‘d’列设置为二级索引
df2
df3 = df2.reset_index().sort_index('columns') # 把多层索引转换为平面数组,并对列进列索引排序
df3