>>> from env_helper import info; info()
页面更新时间: 2023-07-09 19:07:24
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-10-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

7.8. Pandas缺失数据

数据丢失(缺失)在现实生活中总是一个问题。 机器学习和数据挖掘等领域由于数据缺失导致的数据质量差,在模型预测的准确性上面临着严重的问题。 在这些领域,缺失值处理是使模型更加准确和有效的重点。

7.8.1. 何时以及为什么数据丢失?

想象一下有一个产品的在线调查。很多时候,人们不会分享与他们有关的所有信息。 很少有人分享他们的经验,但不是他们使用产品多久; 很少有人分享使用产品的时间,经验,但不是他们的个人联系信息。 因此,以某种方式或其他方式,总会有一部分数据总是会丢失,这是非常常见的现象。

现在来看看如何处理使用 Pandas 的缺失值(如 NANaN )。

>>> 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'])
>>> df
one two three
a 0.903675 -0.758332 0.130283
b NaN NaN NaN
c 1.329166 1.405324 -1.340752
d NaN NaN NaN
e 0.337259 -0.715515 -0.965206
f -0.652424 0.032724 0.048088
g NaN NaN NaN
h 0.298508 0.397356 0.980140

使用重构索引(reindexing),创建了一个缺少值的DataFrame。 在输出中, NaN 表示不是数字的值。

7.8.2. 检查缺失值

为了更容易地检测缺失值(以及跨越不同的数组dtype), 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将被视为0
如果数据全部是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.164226716151406

示例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())
0

7.8.3. 清理/填充缺少数据

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 -1.158906  0.895556  0.855272
b       NaN       NaN       NaN
c  0.687950 -0.575190  1.575458
NaN replaced with '0':
        one       two     three
a -1.158906  0.895556  0.855272
b  0.000000  0.000000  0.000000
c  0.687950 -0.575190  1.575458

在这里填充零值; 当然,也可以填写任何其他的值。

7.8.4. 向前和向后填充 NA

使用重构索引章节讨论的填充概念,来填补缺失的值。

方法

动作

pad/fill

填充方法向前

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.422062 -0.483934 -0.027814
b -0.422062 -0.483934 -0.027814
c -0.330458 -2.232305 -0.969076
d -0.330458 -2.232305 -0.969076
e  0.658659  1.260835  1.325543
f  1.429534 -0.837462  0.021471
g  1.429534 -0.837462  0.021471
h -0.391807 -1.109020  1.430484

示例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 -1.598340 -0.935770 -0.699062
b  1.472813  1.782989 -0.223931
c  1.472813  1.782989 -0.223931
d  0.747313  0.947722 -1.018649
e  0.747313  0.947722 -1.018649
f -0.356098  1.113115 -0.659309
g -1.199901 -2.074105  0.879266
h -1.199901 -2.074105  0.879266

7.8.5. 丢失缺少的值

如果只想排除缺少的值,则使用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  1.006377  1.233967  0.444081
c -0.757340  0.854795 -0.791367
e -0.109504  1.246832  0.681621
f  0.293612  0.895150 -1.176648
h  1.346474 -0.881529 -1.651369

示例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]

7.8.6. 替换丢失(或)通用值

很多时候,必须用一些具体的值取代一个通用的值。可以通过应用替换方法来实现这一点。

用标量值替换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