Pandas之ReIndex重新索引的实现
作者:yungeisme 时间:2023-10-22 20:47:28
约定:
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
代码结果:
one | two | four | |
---|---|---|---|
a | 0 | 1 | 2 |
c | 3 | 4 | 5 |
d | 6 | 7 | 8 |
默认对行索引重新排序
只传入一个序列不能重新排序列索引
df1.reindex(['a','b','c','d'])
代码结果:
one | two | four | |
---|---|---|---|
a | 0.0 | 1.0 | 2.0 |
b | NaN | NaN | NaN |
c | 3.0 | 4.0 | 5.0 |
d | 6.0 | 7.0 | 8.0 |
df1.reindex(index=['a','b','c','d'],columns=['one','two','three','four'])
代码结果:
one | two | three | four | |
---|---|---|---|---|
a | 0.0 | 1.0 | NaN | 2.0 |
b | NaN | NaN | NaN | NaN |
c | 3.0 | 4.0 | NaN | 5.0 |
d | 6.0 | 7.0 | NaN | 8.0 |
传入fill_value=n用n代替缺失值:
df1.reindex(index=['a','b','c','d'],columns=['one','two','three','four'],fill_value=100)
代码结果:
one | two | three | four | |
---|---|---|---|---|
a | 0 | 1 | 100 | 2 |
b | 100 | 100 | 100 | 100 |
c | 3 | 4 | 100 | 5 |
d | 6 | 7 | 100 | 8 |
来源:https://blog.csdn.net/weixin_38168620/article/details/79596702
标签:Pandas,ReIndex,重新索引
0
投稿
猜你喜欢
分析Mysql大量数据导入遇到的问题以及解决方案
2024-01-23 19:10:08
python 地图经纬度转换、纠偏的实例代码
2021-11-06 11:12:18
纯CSS制作的网页中的lightbox效果
2007-11-06 18:59:00
Python中的MongoDB基本操作:连接、查询实例
2021-12-21 07:38:06
MySQL中SQL的单字节注入与宽字节注入
2009-03-25 14:49:00
Python图片存储和访问的三种方式详解
2021-01-27 08:18:22
python异常处理和日志处理方式
2023-04-25 09:36:54
Python项目文件中安装 setup.py的步骤
2023-10-24 15:06:01
Python安装spark的详细过程
2021-05-17 09:59:05
详解Oracle 中实现数据透视表的几种方法
2023-07-24 03:45:04
PyPy 如何让Python代码运行得和C一样快
2022-07-16 20:17:58
如何强制删除或恢复SQLServer正在使用的数据库
2024-01-28 16:16:56
Python数组变形的几种实现方法
2021-08-20 09:30:47
windows10下python3.5 pip3安装图文教程
2023-02-25 02:06:44
MySQL函数CONCAT、CONCAT_WS、GROUP_CONCAT用法详解
2024-01-22 08:57:56
Linux下安装mysql的教程详解
2024-01-20 03:24:37
sql server如何利用开窗函数over()进行分组统计
2024-01-16 01:55:36
python enumerate内置函数用法总结
2023-06-24 05:54:24
python批量检查两个对应的txt文件的行数是否一致的实例代码
2023-10-24 07:56:48
CSS content, counter-increment 和 counter-reset详解[译]
2009-06-02 12:51:00