Pandas:Series和DataFrame的重新索引函数--reindex

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']) # 若无对应值则用NaN填充
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BQW_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值