Python Pandas 缺失数据


在现实生活场景中,缺失数据始终是一个问题。由于缺失值导致数据质量差,机器学习和数据挖掘等领域在模型预测的准确性方面面临严重问题。在这些领域,缺失值处理是使他们的模型更加准确和有效的主要关注点。

何时以及为何会丢失数据?


让我们考虑对产品进行在线调查。很多时候,人们不会分享与他们相关的所有信息。很少有人会分享他们的经验,但不会分享他们使用产品的时间;很少有人会分享他们使用该产品的时间、他们的经验,而不是他们的联系信息。因此,在某些情况下,总是会丢失一部分数据,这在实时情况下非常普遍。

现在让我们看看如何使用 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 对象上的方法:

示例 1

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

示例 2

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'].notnull()

输出如下:

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

缺失数据的计算

  • 对数据求和时,NA 将被视为零

  • 如果数据都是NA,那么结果就是NA

示例 1

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'].sum()

输出如下:

2.02357685917

示例 2

import pandas as pd
import numpy as np

df = pd.DataFrame(index=[0,1,2,3,4,5],columns=['one','two'])
print df['one'].sum()

输出如下:

nan

清理/填充缺失数据


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


使用 ReIndexing 章节中讨论的填充概念,我们将填充缺失值。

序号方法与行动
1

pad/fill

填充方法前进

2

bfill/backfill

向后填充方法

示例 1

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

示例 2

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='backfill')

输出如下:

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

删除缺失值


如果你想简单地排除缺失的值,那么请使用dropna函数和axis参数。默认情况下,axis=0,即沿行,这意味着如果某行内的任何数值是NA,那么整个行都被排除。

示例 1

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

示例 2

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(axis=1)

输出如下:

Empty DataFrame
Columns: [ ]
Index: [a, b, c, d, e, f, g, h]

替换缺失的(或)通用值


很多时候,我们必须用某个特定值替换通用值。我们可以通过应用替换方法来实现这一点。

用标量值替换 NA 是fillna()功能。

示例 1

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

示例 2

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