Python Pandas - 填充缺失資料



填充缺失資料是一個用有意義的替代方案替換缺失 (NaN) 值的過程。無論您是想用常量值替換缺失值,還是向前或向後傳播值,Pandas 都內建了函式來實現這一點。

在本教程中,我們將學習在 Pandas 中填充缺失資料的不同方法,包括:

  • 用標量替換缺失值。

  • 向前和向後填充。

  • 使用指定的限制進行填充。

  • 使用 replace() 方法替換資料。

  • 使用正則表示式替換值。

用標量值填充缺失資料

Pandas 中的 fillna() 方法用於用標量值(例如任何特定數字)填充缺失值 (NA 或 NaN)。

示例

以下演示瞭如何使用 fillna() 方法用標量值(“NaN” 為 “5”)填充缺失值 NaN。

import pandas as pd
import numpy as np

# Create DataFrame with missing values
data = {"Col1": [3, np.nan, np.nan, 2], "Col2": [1.0, pd.NA, pd.NA, 2.0]}
df = pd.DataFrame(data)

# Display the original DataFrame with missing values
print("Original DataFrame:\n",df)

# Fill missing values with 5
df_filled = df.fillna(5)
print("\nResultant DataFrame after NaN replaced with '5':\n", df_filled)

輸出如下:

Original DataFrame:
Col1Col2
03.01.0
1NaN<NA>
2NaN<NA>
32.02.0
Resultant DataFrame after NaN replaced with '0':
Col1Col2
03.01.0
15.05.0
25.05.0
32.02.0

向前或向後填充缺失值

您還可以分別使用 ffill()bfill() 方法傳播最後一個有效觀測值以向前或向後填充間隙。

序號 方法和操作
1

ffill()

此方法用前一個有效值填充缺失值。

2

bfill()

此方法用下一個有效值填充缺失值。

示例:向前填充

此示例使用向前填充 ffill() 方法替換缺失值。

import pandas as pd
import numpy as np

# Create DataFrame with missing values
df = pd.DataFrame([[9, -3, -2], [-5, 1, 8], [6, 4, -8]], 
index=['a', 'c', 'd'], columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e'])
 
# Display the original DataFrame with missing values
print("Original DataFrame:\n",df)

# Forward Fill the missing values
result = df.ffill()
print("\nResultant DataFrame after Forward fill:\n", result)

輸出如下:

Original DataFrame:
onetwothree
a9.0-3.0-2.0
bNaNNaNNaN
c-5.01.08.0
d6.04.0-8.0
eNaNNaNNaN
Resultant DataFrame after Forward fill:
onetwothree
a9.0-3.0-2.0
b9.0-3.0-2.0
c-5.01.08.0
d6.04.0-8.0
e6.04.0-8.0

示例:向後填充

此示例使用向後填充 bfill() 方法替換缺失值。

import pandas as pd
import numpy as np

# Create DataFrame with missing values
df = pd.DataFrame([[9, -3, -2], [-5, 1, 8], [6, 4, -8]], 
index=['a', 'c', 'd'], columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e'])
 
# Display the original DataFrame with missing values
print("Original DataFrame:\n",df)

# Backward Fill the missing values
result = df.bfill()
print("\nResultant DataFrame after Backward fill:\n", result)

輸出如下:

Original DataFrame:
onetwothree
a9.0-3.0-2.0
bNaNNaNNaN
c-5.01.08.0
d6.04.0-8.0
eNaNNaNNaN
Resultant DataFrame after Backward fill:
onetwothree
a9.0-3.0-2.0
b-5.01.08.0
c-5.01.08.0
d6.04.0-8.0
eNaNNaNNaN

限制填充次數

您還可以透過指定 limit 引數來控制填充多少個連續缺失值的限制。

示例

以下示例演示瞭如何使用 limit 引數使用 ffill() 方法設定填充缺失值的限制。

import pandas as pd
import numpy as np

# Create DataFrame with missing values
df = pd.DataFrame([[9, -3, -2], [-5, 1, 8], [6, 4, -8]], 
index=['a', 'c', 'd'], columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'd', 'e', 'f'])
 
# Display the original DataFrame with missing values
print("Original DataFrame:\n",df)

# Forward Fill the missing values with limit
result = df.ffill(limit=1)
print("\nResultant DataFrame after Forward fill:\n", result)

以下是上述程式碼的輸出:

Original DataFrame:
onetwothree
a9.0-3.0-2.0
bNaNNaNNaN
d6.04.0-8.0
eNaNNaNNaN
fNaNNaNNaN
Resultant DataFrame after Forward fill:
onetwothree
a9.0-3.0-2.0
b9.0-3.0-2.0
d6.04.0-8.0
e6.04.0-8.0
fNaNNaNNaN

使用 replace() 方法替換資料

很多時候,我們必須用一些特定值替換通用值。我們可以透過應用 replace() 方法來實現。

用標量值替換 NA 等效於 fillna() 函式的行為。

示例

以下是使用 replace() 方法替換通用值的示例。

import pandas as pd
import numpy as np

# Create DataFrame 
df = pd.DataFrame({'one':[10,20,30,40,50,2000], 'two':[1000,0,30,40,50,60]})

# Replace the generic values
print(df.replace({1000:10,2000:60}))

輸出如下:

one two
0 10 10
1 20 0
2 30 30
3 40 40
4 50 50
5 60 60

使用正則表示式替換缺失資料

您還可以使用正則表示式模式用 replace() 方法替換資料中的缺失值。

示例

以下是使用正則表示式用 replace() 方法替換特定資料的示例。

import pandas as pd
import numpy as np

# Create DataFrame with missing values
df = pd.DataFrame({"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]})

# Display the original DataFrame with missing values
print("Original DataFrame:\n",df)

# Replace the missing values with regular exp
result = df.replace(r"\.", 10, regex=True)

print("\nResultant DataFrame after filling the missing values using regex:\n", result)

輸出如下:

Original DataFrame:
abc
00aa
11bb
22.NaN
33.d
Resultant DataFrame after filling the missing values using regex:
abc
00aa
11bb
2210NaN
3310d
廣告