pandas入门(3):处理缺失数据

missing data

pandas对象上的所有描述统计都排除了缺失数据。

pandas用NaN(Not a Number)表示浮点数和非浮点数组中的缺失数据,它只是一个便于检测的标记而已。

滤除缺失数据(dropna):

dropna
对于一个Seriesdropna返回一个仅含非空数据和索引值的Series

In [55]: from numpy import nan as NA

In [56]: data = Series([1, NA, 3.5, NA, 7])

In [57]: data.dropna()
Out[57]: 
0    1.0
2    3.5
4    7.0
dtype: float64

而对于DataFrame对象,情况有点复杂:dropna默认丢弃任何含有缺失的行:

In [58]: data = DataFrame([[1., 6.5, 3.], [1., NA, NA], [NA, NA, NA], [NA, 6.5, 3.]])
In [59]: cleaned = data.dropna()

In [60]: data
Out[60]: 
     0    1    2
0  1.0  6.5  3.0
1  1.0  NaN  NaN
2  NaN  NaN  NaN
3  NaN  6.5  3.0

In [62]: cleaned
Out[62]: 
     0    1    2
0  1.0  6.5  3.0

传入 how = 'all'将只丢弃全部为NA的行:

In [63]: data.dropna(how='all')
Out[63]: 
     0    1    2
0  1.0  6.5  3.0
1  1.0  NaN  NaN
3  NaN  6.5  3.0

丢弃列传入axis=1即可

填补缺失数据(fillna):

对于大多数情况而言,fillna方法是主要的函数:
通过一个常数调用fillna就会将缺失值替换为那个常数值:

In [70]: df.fillna(0)
Out[70]: 
          0         1         2
0  1.399904  0.000000  0.000000
1  1.575537  0.000000  0.000000
2 -0.331882  0.000000 -0.649257
3  0.098962  0.000000 -0.488681
4  0.816113  0.578439 -0.255484
5 -0.794037 -0.190817 -1.670218
6 -0.319344  0.112990  1.457793

如果通过一个字典调用fillna,就可以实现对不同的列填充不同的值:

In [71]: df.fillna({1:0.5, 3:-1})
Out[71]: 
          0         1         2
0  1.399904  0.500000       NaN
1  1.575537  0.500000       NaN
2 -0.331882  0.500000 -0.649257
3  0.098962  0.500000 -0.488681
4  0.816113  0.578439 -0.255484
5 -0.794037 -0.190817 -1.670218
6 -0.319344  0.112990  1.457793

fillna默认返回新对象,也可以对现有对象进行就地修改:

In [72]: _ = df.fillna(0, inplace=True)

In [73]: df
Out[73]: 
          0         1         2
0  1.399904  0.000000  0.000000
1  1.575537  0.000000  0.000000
2 -0.331882  0.000000 -0.649257
3  0.098962  0.000000 -0.488681
4  0.816113  0.578439 -0.255484
5 -0.794037 -0.190817 -1.670218
6 -0.319344  0.112990  1.457793

reindex有效的那些插值方法也可用于fillna

In [75]: df = DataFrame(np.random.randn(6,3))
In [76]: df.iloc[:2, 1] = NA; df.iloc[4:, 2] = NA

In [77]: df
Out[77]: 
          0         1         2
0  0.877356       NaN -1.775499
1 -0.599936       NaN  0.891599
2 -0.234968 -0.438411  1.519332
3 -1.026612  0.409573  0.667059
4 -1.491810 -0.316408       NaN
5 -0.185388  0.778041       NaN

In [78]: df.fillna(method='ffill')
Out[78]: 
          0         1         2
0  0.877356       NaN -1.775499
1 -0.599936       NaN  0.891599
2 -0.234968 -0.438411  1.519332
3 -1.026612  0.409573  0.667059
4 -1.491810 -0.316408  0.667059
5 -0.185388  0.778041  0.667059

In [79]: df.fillna(method='ffill', limit=2)
Out[79]: 
          0         1         2
0  0.877356       NaN -1.775499
1 -0.599936       NaN  0.891599
2 -0.234968 -0.438411  1.519332
3 -1.026612  0.409573  0.667059
4 -1.491810 -0.316408  0.667059
5 -0.185388  0.778041  0.667059

你可能感兴趣的:(pandas入门(3):处理缺失数据)