Python - 資料清洗



在現實生活場景中,缺失資料始終是一個問題。機器學習和資料探勘等領域由於資料質量差(由缺失值造成)導致模型預測準確性出現嚴重問題。在這些領域,缺失值處理是提高模型準確性和有效性的一個主要關注點。

資料何時以及為何缺失?

讓我們考慮一個產品的線上調查。很多時候,人們不會分享與他們相關的所有資訊。一些人分享他們的體驗,但沒有分享他們使用產品的時長;一些人分享他們使用產品的時長、他們的體驗,但沒有分享他們的聯絡方式。因此,資料的一部分總是以某種方式缺失,這在即時資料中非常常見。

現在讓我們看看如何使用 Pandas 處理缺失值(例如 NA 或 NaN)。

# import the pandas library
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])

df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

print df

輸出如下所示:

         one        two      three
a   0.077988   0.476149   0.965836
b        NaN        NaN        NaN
c  -0.390208  -0.551605  -2.301950
d        NaN        NaN        NaN
e  -2.000303  -0.788201   1.510072
f  -0.930230  -0.670473   1.146615
g        NaN        NaN        NaN
h   0.085100   0.532791   0.887415

使用重新索引,我們建立了一個包含缺失值的 DataFrame。在輸出中,NaN 表示非數字

檢查缺失值

為了更容易檢測缺失值(並在不同的陣列資料型別中),Pandas 提供了isnull()notnull() 函式,它們也是 Series 和 DataFrame 物件上的方法:

示例

import pandas as pd
import numpy as np
 
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])

df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

print df['one'].isnull()

輸出如下所示:

a  False
b  True
c  False
d  True
e  False
f  False
g  True
h  False
Name: one, dtype: bool

清理/填充缺失資料

Pandas 提供了多種清理缺失值的方法。fillna 函式可以通過幾種方式“填充” NA 值為非空資料,我們在以下部分進行了說明。

用標量值替換 NaN

以下程式展示瞭如何用“0”替換“NaN”。

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],columns=['one',
'two', 'three'])
df = df.reindex(['a', 'b', 'c'])
print df
print ("NaN replaced with '0':")
print df.fillna(0)

輸出如下所示:

         one        two     three
a  -0.576991  -0.741695  0.553172
b        NaN        NaN       NaN
c   0.744328  -1.735166  1.749580

NaN replaced with '0':
         one        two     three
a  -0.576991  -0.741695  0.553172
b   0.000000   0.000000  0.000000
c   0.744328  -1.735166  1.749580

這裡,我們用值零填充;我們也可以用任何其他值填充。

向前和向後填充 NA

使用在重新索引章節中討論的填充概念,我們將填充缺失值。

方法 操作
pad/fill 向前填充方法
bfill/backfill 向後填充方法

示例

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])

print df.fillna(method='pad')

輸出如下所示:

         one        two      three
a   0.077988   0.476149   0.965836
b   0.077988   0.476149   0.965836
c  -0.390208  -0.551605  -2.301950
d  -0.390208  -0.551605  -2.301950
e  -2.000303  -0.788201   1.510072
f  -0.930230  -0.670473   1.146615
g  -0.930230  -0.670473   1.146615
h   0.085100   0.532791   0.887415

刪除缺失值

如果您只想排除缺失值,則可以使用dropna 函式以及axis 引數。預設情況下,axis=0,即沿行,這意味著如果一行中的任何值為 NA,則整行都會被排除。

示例

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',
'h'],columns=['one', 'two', 'three'])

df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print df.dropna()

輸出如下所示:

         one        two      three
a   0.077988   0.476149   0.965836
c  -0.390208  -0.551605  -2.301950
e  -2.000303  -0.788201   1.510072
f  -0.930230  -0.670473   1.146615
h   0.085100   0.532791   0.887415

替換缺失值(或)通用值

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

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

示例

import pandas as pd
import numpy as np
df = pd.DataFrame({'one':[10,20,30,40,50,2000],
'two':[1000,0,30,40,50,60]})
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
廣告

© . All rights reserved.