import numpy as np
import pandas as pd
from pandas import Series,DataFrame
一、reindex函数的参数
参数 | 说明 |
---|
index | 用作索引的新序列。即可以是Index实例,也可以是其他序列型的Python数据结构。Index会被完全使用,就像没有任何复制一样 |
method | 插值方式 |
fill_value | 在重新索引的过程中,需要引入缺失值时使用的替代值 |
limit | 前向或后向填充时的最大填充量 |
level | 在MultiIndex的指定级别上匹配简单索引,否则选取其子集 |
copy | 默认为True,无论如何都复制;如果为False,则新旧相等就不复制 |
二、Series的reindex
o = Series([1,3,4,7],index=['d','c','b','a'])
print(o)
d 1
c 3
b 4
a 7
dtype: int64
1.重新索引
o1 = o.reindex(['a','b','c','d','e'])
print(o1)
a 7.0
b 4.0
c 3.0
d 1.0
e NaN
dtype: float64
2.使用fill_value参数填充缺失值
o2 = o.reindex(['a','b','c','d','e'],fill_value=0)
print(o2)
a 7
b 4
c 3
d 1
e 0
dtype: int64
三、DataFrame的reindex
data = {'水果':['苹果','梨','草莓'],
'数量':[3,2,5],
'价格':[10,9,8]}
df = DataFrame(data)
1.对行进行重索引(默认)
print(df.reindex([2,0,1]))
价格 数量 水果
2 8 5 草莓
0 10 3 苹果
1 9 2 梨
2.对列进行重索引(columns参数)
print(df.reindex(columns=['水果','数量','价格']))
水果 数量 价格
0 苹果 3 10
1 梨 2 9
2 草莓 5 8
3.同时对行和列进行重索引
print(df.reindex([2,0,1],columns=['水果','数量','价格']))
水果 数量 价格
2 草莓 5 8
0 苹果 3 10
1 梨 2 9
四、使用loc/iloc实现更简洁的重索引
print(df.loc[[2,0,1],['水果','数量','价格']])
水果 数量 价格
2 草莓 5 8
0 苹果 3 10
1 梨 2 9