Pandas详解八之ReIndex重新索引

约定:
import pandas as pd
import numpy as np

ReIndex重新索引

reindex()是pandas对象的一个重要方法,其作用是创建一个新索引的新对象。

一、对Series对象重新索引

se1=pd.Series([1,7,3,9],index=['d','c','a','f'])
se1

代码结果:

d    1
c    7
a    3
f    9
dtype: int64
  • 调用reindex将会重新排序,缺失值则用NaN填补。
se2=se1.reindex(['a','b','c','d','e','f'])
se2

代码结果:

a    3.0
b    NaN
c    7.0
d    1.0
e    NaN
f    9.0
dtype: float64
  • 传入method=” “重新索引时选择插值处理方式:

method=’ffill’或’pad 前向填充

method=’bfill’或’backfill 后向填充

se3=pd.Series(['blue','red','black'],index=[0,2,4])
se4=se3.reindex(range(6),method='ffill')
se4

代码结果:

0     blue
1     blue
2      red
3      red
4    black
5    black
dtype: object

二、对DataFrame对象重新索引

对于DataFrame对象,reindex能修改行索引和列索引。

df1=pd.DataFrame(np.arange(9).reshape(3,3),index=['a','c','d'],columns=['one','two','four'])
df1
代码结果:
onetwofour
a012
c345
d678
  • 默认对行索引重新排序

只传入一个序列不能重新排序列索引

df1.reindex(['a','b','c','d'])
代码结果:
onetwofour
a0.01.02.0
bNaNNaNNaN
c3.04.05.0
d6.07.08.0
df1.reindex(index=['a','b','c','d'],columns=['one','two','three','four'])
代码结果:
onetwothreefour
a0.01.0NaN2.0
bNaNNaNNaNNaN
c3.04.0NaN5.0
d6.07.0NaN8.0
  • 传入fill_value=n用n代替缺失值:
df1.reindex(index=['a','b','c','d'],columns=['one','two','three','four'],fill_value=100)
代码结果:
onetwothreefour
a011002
b100100100100
c341005
d671008

谢谢大家的浏览,
希望我的努力能帮助到您,
共勉!

  • 67
    点赞
  • 140
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值