今天就跟大家聊聊有關如何在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
代碼結果:
| 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 |
看完上述內容,你們對如何在Pandas中實現ReIndex重新索引有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。