Python Pandas - 重新索引



重新索引是 Pandas 中一個強大且基本的操作,允許您將資料與一組新的標籤對齊。無論您使用的是行還是列,重新索引都可以控制資料如何與您指定的標籤對齊。

此操作在處理時間序列資料、對齊來自不同來源的資料集或簡單地重新組織資料以匹配特定結構時特別有用。

什麼是重新索引?

Pandas 中的重新索引是指使您的資料符合指定軸(行或列)上的一組新標籤的過程。此過程可以完成以下幾個任務:

  • 重新排序:重新排序現有資料以匹配一組新的標籤。

  • 插入缺失值:如果新集合中的標籤在原始資料中不存在,Pandas 將為該標籤插入缺失值 (NaN)。

  • 填充缺失資料:您可以指定如何使用各種填充方法來填充重新索引導致的缺失值。

reindex() 方法是 Pandas 中執行重新索引的主要工具。它允許您修改 Pandas 資料結構的行和列標籤。

重新索引中使用的關鍵方法

  • reindex():此方法用於將現有資料結構與新的索引(或列)對齊。它可以重新排序和/或插入缺失的標籤。

  • reindex_like():此方法允許您將一個 DataFrame 或 Series 重新索引以匹配另一個。當您希望確保兩個資料結構類似地對齊時,此方法很有用。

  • 填充方法:當重新索引引入 NaN 值時,您可以使用 ffill、bfill 和 nearest 等方法填充它們。

示例:重新索引 Pandas Series

以下示例演示了使用 reindex() 方法重新索引 Pandas Series 物件。在這種情況下,“f”標籤在原始 Series 中不存在,因此它在輸出重新索引的 Series 中顯示為 NaN。

import pandas as pd
import numpy as np

s = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"])
print("Original Series:\n",s)

s_reindexed = s.reindex(["e", "b", "f", "d"])
print('\nOutput Reindexed Series:\n',s_reindexed)

執行上述程式碼後,您將獲得以下輸出:

Original Series:
 a    0.148874
b    0.592275
c   -0.903546
d    1.031230
e   -0.254599
dtype: float64

Output Reindexed Series:
 e   -0.254599
b    0.592275
f         NaN
d    1.031230
dtype: float64

示例:重新索引 DataFrame

考慮以下使用 reindex() 方法重新索引 DataFrame 的示例。對於 DataFrame,您可以重新索引行(索引)和列。

import pandas as pd
import numpy as np

N=5

df = pd.DataFrame({
   'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),
   'x': np.linspace(0,stop=N-1,num=N),
   'y': np.random.rand(N),
   'C': np.random.choice(['Low','Medium','High'],N).tolist(),
   'D': np.random.normal(100, 10, size=(N)).tolist()
})

print("Original DataFrame:\n", df)

#reindex the DataFrame
df_reindexed = df.reindex(index=[0,2,5], columns=['A', 'C', 'B'])

print("\nOutput Reindexed DataFrame:\n",df_reindexed)

輸出如下:

Original DataFrame:
            A    x         y       C           D
0 2016-01-01  0.0  0.513990  Medium  118.143385
1 2016-01-02  1.0  0.751248     Low   91.041201
2 2016-01-03  2.0  0.332970  Medium  100.644345
3 2016-01-04  3.0  0.723816    High  108.810386
4 2016-01-05  4.0  0.376326    High  101.346443

Output Reindexed DataFrame:
            A       C   B
0 2016-01-01  Medium NaN
2 2016-01-03  Medium NaN
5        NaT     NaN NaN

重新索引以與其他物件對齊

有時,您可能需要重新索引一個 DataFrame 以使其與另一個 DataFrame 對齊。reindex_like() 方法允許您無縫地執行此操作。

示例

以下示例演示瞭如何使用 reindex_like() 方法重新索引一個 DataFrame (df1) 以匹配另一個 DataFrame (df2)。

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(10,3),columns=['col1','col2','col3'])
df2 = pd.DataFrame(np.random.randn(7,3),columns=['col1','col2','col3'])

df1 = df1.reindex_like(df2)
print(df1)

輸出如下:

          col1         col2         col3
0    -2.467652    -1.211687    -0.391761
1    -0.287396     0.522350     0.562512
2    -0.255409    -0.483250     1.866258
3    -1.150467    -0.646493    -0.222462
4     0.152768    -2.056643     1.877233
5    -1.155997     1.528719    -1.343719
6    -1.015606    -1.245936    -0.295275

注意:此處,df1 DataFrame 被更改並像 df2 一樣重新索引。列名應匹配,否則將為整個列標籤新增 NAN。

重新索引時的填充

reindex() 方法提供了一個可選引數 method 用於填充缺失值。可用的方法包括:

  • pad/ffill:向前填充值。

  • bfill/backfill:向後填充值。

  • nearest:從最近的索引值填充。

示例

以下示例演示了 ffill 方法的工作原理。

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(6, 3), columns=['col1', 'col2', 'col3'])
df2 = pd.DataFrame(np.random.randn(2, 3), columns=['col1', 'col2', 'col3'])

# Padding NaNs
print(df2.reindex_like(df1))

# Now fill the NaNs with preceding values
print("Data Frame with Forward Fill:")
print(df2.reindex_like(df1, method='ffill'))

輸出如下:

         col1        col2       col3
0    1.311620   -0.707176   0.599863
1   -0.423455   -0.700265   1.133371
2         NaN         NaN        NaN
3         NaN         NaN        NaN
4         NaN         NaN        NaN
5         NaN         NaN        NaN

Data Frame with Forward Fill:
         col1        col2        col3
0    1.311620   -0.707176    0.599863
1   -0.423455   -0.700265    1.133371
2   -0.423455   -0.700265    1.133371
3   -0.423455   -0.700265    1.133371
4   -0.423455   -0.700265    1.133371
5   -0.423455   -0.700265    1.133371

注意:最後四行已填充。

重新索引時填充的限制

limit 引數提供了對重新索引時填充的額外控制。limit 指定連續匹配的最大計數。

示例

讓我們考慮以下示例來了解指定填充限制:

import pandas as pd
import numpy as np
 
df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])
df2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3'])

# Padding NaNs
print(df2.reindex_like(df1))

# Now fill the NaNs with preceding values
print("Data Frame with Forward Fill limiting to 1:")
print(df2.reindex_like(df1, method='ffill', limit=1))

輸出如下:

         col1        col2        col3
0    0.247784    2.128727    0.702576
1   -0.055713   -0.021732   -0.174577
2         NaN         NaN         NaN
3         NaN         NaN         NaN
4         NaN         NaN         NaN
5         NaN         NaN         NaN

Data Frame with Forward Fill limiting to 1:
         col1        col2        col3
0    0.247784    2.128727    0.702576
1   -0.055713   -0.021732   -0.174577
2   -0.055713   -0.021732   -0.174577
3         NaN         NaN         NaN
4         NaN         NaN         NaN
5         NaN         NaN         NaN

注意:向前填充 (ffill) 僅限於一行。

廣告