網站首頁 編程語言 正文
Pandas DataFrame之重新索引
1.reindex可以對行和列索引
默認對行索引,加上關鍵字columns對列索引。
import pandas as pd
data=[[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
df = pd.DataFrame(data,index=['d','b','c','a'])
print(df)
默認對列索引:如果是新的索引名將會用NaN
df=df.reindex(['a','b','c','d','e'])
print(df)
加上關鍵字columns對列重新索引:
df=df.reindex(columns=[2,1,3,4,0])
print(df)
2.reindex插值處理
對于index為有序的數據,我們有時候可能會進行一些插值處理,只需要在reindex加上method參數即可,參數如下表
(圖片來源:截圖于 利用python進行數據分析 Wes McKinney 著)
例子:
import pandas as pd
data=[[1,1,1,1],[2,2,2,2],[3,3,3,3]]
df = pd.DataFrame(data,index=range(3))
print(df)
df=df.reindex([0,1,2,3,4,5],method='ffill')
print('--------------')
print(df)
reindex函數的相關參數:
(圖片來源:截圖于 利用python進行數據分析 Wes McKinney 著)
Pandas DataFrame重置索引案例
import pandas as pd
import numpy as np
a=pd.DataFrame(np.random.randint(1,10,20).reshape(4,5))
print(a)
0 1 2 3 4
0 1 3 2 7 6
1 8 2 2 7 2
2 2 6 6 2 5
3 4 1 6 8 9
b=a.sort_values(by=4)
print(b)
0 1 2 3 4
1 8 2 2 7 2
2 2 6 6 2 5
0 1 3 2 7 6
3 4 1 6 8 9
### 重置索引:方法1
c=a.sort_values(by=4,ignore_index=True)
print(c)
0 1 2 3 4
0 8 2 2 7 2
1 2 6 6 2 5
2 1 3 2 7 6
3 4 1 6 8 9
### 重置索引:方法2
d=b.reset_index(drop=True)
print(d)
0 1 2 3 4
0 8 2 2 7 2
1 2 6 6 2 5
2 1 3 2 7 6
3 4 1 6 8 9
原文鏈接:https://blog.csdn.net/baishengxu/article/details/81349451
相關推薦
- 2022-08-16 Docker中部署Redis集群與部署微服務項目的詳細過程_docker
- 2023-10-16 微信小程序瀏覽docx,pdf等文件在線預覽使用wx.openDocument
- 2022-04-24 python使用技巧-查找文件?_python
- 2023-07-02 Python基于歐拉角繪制一個立方體_python
- 2023-02-05 expect實現Linux自動登陸遠程機器腳本實例_Linux
- 2023-01-09 No?module?named?'plotly.graph_objects'報錯解決_python
- 2022-09-22 SGL:Self-supervised Graph Learning for Recommendat
- 2021-12-18 C++?STL容器詳解之紅黑樹部分模擬實現_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支