pandas的基本用法(四)——处理缺失数据

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要是关于pandas的一些基本用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
# _*_ coding: utf-8 _*_

import pandas as pd
import numpy as np


# Test 1
# 定义数据
dates = pd.date_range('20170101', periods = 6)
df = pd.DataFrame(np.arange(24).reshape((6, 4)), index = dates, columns = ['A', 'B', 'C', 'D'])

# 假设缺少数据
df.iloc[1, 1] = np.nan
df.iloc[2, 2] = np.nan
print df

# Test 1 result
A B C D
2017-01-01 0 1.0 2.0 3
2017-01-02 4 NaN 6.0 7
2017-01-03 8 9.0 NaN 11
2017-01-04 12 13.0 14.0 15
2017-01-05 16 17.0 18.0 19
2017-01-06 20 21.0 22.0 23

# Test 2
# 按行或列来舍弃数据, how = any or all, any是默认值
print df.dropna(axis = 0, how = 'any')

# 填充数据
print df.fillna(value = 0)

# 判断是否缺失数据
print df.isnull()

# 判断是否存在缺失数据的情况
print np.any(df.isnull() == True)

# Test 2 result
A B C D
2017-01-01 0 1.0 2.0 3
2017-01-04 12 13.0 14.0 15
2017-01-05 16 17.0 18.0 19
2017-01-06 20 21.0 22.0 23

A B C D
2017-01-01 0 1.0 2.0 3
2017-01-02 4 0.0 6.0 7
2017-01-03 8 9.0 0.0 11
2017-01-04 12 13.0 14.0 15
2017-01-05 16 17.0 18.0 19
2017-01-06 20 21.0 22.0 23

A B C D
2017-01-01 False False False False
2017-01-02 False True False False
2017-01-03 False False True False
2017-01-04 False False False False
2017-01-05 False False False False
2017-01-06 False False False False

True

参考资料

  1. https://www.youtube.com/user/MorvanZhou
如果有收获,可以请我喝杯咖啡!