工程与学习方法 / 30.1

数据处理:pandas与预处理

工具、语法与实践中的边界。 数据处理:pandas与预处理。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

Objectives

  • Learn Pandas Basics

Things need to know

  • 对于0基础的同学,以了解为主
  • 不需要可以从0把code写出来
  • 这部分code与算法课程code的思维不一样
  • 需要下课自己去跑一下code,尽量去理解
  • 工具终归是辅助我们的,先尽力学会一个
  • 逐步掌握python code debug能力

Pandas

Pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Additionally, it has the broader goal of becoming the most powerful and flexible open source data analysis / manipulation tool available in any language. It is already well on its way toward this goal.

The two primary data structures of pandas, Series (1-dimensional) and DataFrame (2-dimensional), handle the vast majority of typical use cases in finance, statistics, social science, and many areas of engineering. pandas is built on top of NumPy and is intended to integrate well within a scientific computing environment with many other 3rd party libraries.

Load Data

PYTHON · 仅供阅读
import numpy as np
import pandas as pd
PYTHON · 仅供阅读
# read data from URL
# iris = 'https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/639388c2cbc2120a14dcf466e85730eb8be498bb/iris.csv'
iris = 'iris.csv'
df_iris = pd.read_csv(iris, sep=',') #tsv 
print(type(df_iris))
原笔记输出 · 本次未执行
<class 'pandas.core.frame.DataFrame'>
PYTHON · 仅供阅读
# Read data from Google Drive (recommend)
# Get sharable link and change the permission to "Anyone with the link can view"
# https://drive.google.com/file/d/[FILE_ID]/view?usp=sharing
# format: /d/<id>/view
# copy out the id: [FILE_ID]
# replace the string in file_id

# file_id='[FILE_ID]'
# link='http://drive.google.com/uc?export=download&id={FILE_ID}'
# csv_url=link.format(FILE_ID=file_id)

csv_url = 'uk_rain_2014.csv'  # For local jupyter lab
df_uk_rain = pd.read_csv(csv_url)
PYTHON · 仅供阅读
print(type(df_uk_rain))
原笔记输出 · 本次未执行
<class 'pandas.core.frame.DataFrame'>
PYTHON · 仅供阅读
df_uk_rain.columns
原笔记输出 · 本次未执行
Index(['Water Year', 'Rain (mm) Oct-Sep', 'Outflow (m3/s) Oct-Sep',
       'Rain (mm) Dec-Feb', 'Outflow (m3/s) Dec-Feb', 'Rain (mm) Jun-Aug',
       'Outflow (m3/s) Jun-Aug'],
      dtype='object')
PYTHON · 仅供阅读
df_uk_rain.columns = ['water_year','rain_octsep', 'outflow_octsep',
              'rain_decfeb', 'outflow_decfeb', 'rain_junaug', 'outflow_junaug']
PYTHON · 仅供阅读
df_uk_rain.columns
原笔记输出 · 本次未执行
Index(['water_year', 'rain_octsep', 'outflow_octsep', 'rain_decfeb',
       'outflow_decfeb', 'rain_junaug', 'outflow_junaug'],
      dtype='object')
PYTHON · 仅供阅读
df_uk_rain.head() #default to be top 5 rows
原笔记输出 · 本次未执行
   water_year  rain_octsep  outflow_octsep  rain_decfeb  outflow_decfeb  \
0        1980         1182            5408          292            7248   
1        1981         1098            5112          257            7316   
2        1982         1156            5701          330            8567   
3        1983          993            4265          391            8905   
4        1984         1182            5364          217            5813   

   rain_junaug  outflow_junaug  
0          174            2212  
1          242            1936  
2          124            1802  
3          141            1078  
4          343            4313
PYTHON · 仅供阅读
# https://colab.sandbox.google.com/notebooks/io.ipynb

Data Structure

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index.

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.

PYTHON · 仅供阅读
# Series from list
s = pd.Series([1,3,5,6,8])

print(type(s))
s
原笔记输出 · 本次未执行
<class 'pandas.core.series.Series'>
原笔记输出 · 本次未执行
0    1
1    3
2    5
3    6
4    8
dtype: int64
PYTHON · 仅供阅读
# Dataframe from dictionary
d = pd.DataFrame({'col1': [1,2,3,4,5,6],'col2': ['1', '2', '3', '4', '5', '6'], 'col3': ['1',2,3,4,5, None]})
print(d)
原笔记输出 · 本次未执行
   col1 col2  col3
0     1    1     1
1     2    2     2
2     3    3     3
3     4    4     4
4     5    5     5
5     6    6  None
PYTHON · 仅供阅读
d.info()
原笔记输出 · 本次未执行
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   col1    6 non-null      int64 
 1   col2    6 non-null      object
 2   col3    5 non-null      object
dtypes: int64(1), object(2)
memory usage: 272.0+ bytes
PYTHON · 仅供阅读
df_iris.info()
原笔记输出 · 本次未执行
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   sepal_length  150 non-null    float64
 1   sepal_width   150 non-null    float64
 2   petal_length  150 non-null    float64
 3   petal_width   150 non-null    float64
 4   species       150 non-null    object 
dtypes: float64(4), object(1)
memory usage: 6.0+ KB
PYTHON · 仅供阅读
# Dataframe first 5(default) rows
df_iris.head(10)
原笔记输出 · 本次未执行
   sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa
3           4.6          3.1           1.5          0.2  setosa
4           5.0          3.6           1.4          0.2  setosa
5           5.4          3.9           1.7          0.4  setosa
6           4.6          3.4           1.4          0.3  setosa
7           5.0          3.4           1.5          0.2  setosa
8           4.4          2.9           1.4          0.2  setosa
9           4.9          3.1           1.5          0.1  setosa
PYTHON · 仅供阅读
df_iris.tail()
原笔记输出 · 本次未执行
     sepal_length  sepal_width  petal_length  petal_width    species
145           6.7          3.0           5.2          2.3  virginica
146           6.3          2.5           5.0          1.9  virginica
147           6.5          3.0           5.2          2.0  virginica
148           6.2          3.4           5.4          2.3  virginica
149           5.9          3.0           5.1          1.8  virginica
PYTHON · 仅供阅读
# Dataframe stats information
df_iris.describe()
原笔记输出 · 本次未执行
       sepal_length  sepal_width  petal_length  petal_width
count    150.000000   150.000000    150.000000   150.000000
mean       5.843333     3.054000      3.758667     1.198667
std        0.828066     0.433594      1.764420     0.763161
min        4.300000     2.000000      1.000000     0.100000
25%        5.100000     2.800000      1.600000     0.300000
50%        5.800000     3.000000      4.350000     1.300000
75%        6.400000     3.300000      5.100000     1.800000
max        7.900000     4.400000      6.900000     2.500000
PYTHON · 仅供阅读
# column data type
df_iris.dtypes
原笔记输出 · 本次未执行
sepal_length    float64
sepal_width     float64
petal_length    float64
petal_width     float64
species          object
dtype: object
PYTHON · 仅供阅读
# index info
print(df_iris.index)
原笔记输出 · 本次未执行
RangeIndex(start=0, stop=150, step=1)
PYTHON · 仅供阅读
df_iris.columns
原笔记输出 · 本次未执行
Index(['sepal_length', 'sepal_width', 'petal_length', 'petal_width',
       'species'],
      dtype='object')
PYTHON · 仅供阅读
# change column names
# pd.DataFrame.rename
attributes = ["sepal_length", "sepal_width", "petal_length", "petal_width", "class"]
df_iris.columns = attributes

df_iris.head(1)
原笔记输出 · 本次未执行
   sepal_length  sepal_width  petal_length  petal_width   class
0           5.1          3.5           1.4          0.2  setosa
PYTHON · 仅供阅读
#iris dataset
#google dataset search
#https://datasetsearch.research.google.com/

Indexing and Slicing

PYTHON · 仅供阅读
# use [] square brackets
df1 = df_iris['sepal_length']  # Series
print(df1.head())
print(type(df1))

df2 = df_iris[['sepal_length']]  # DataFrame
print(df2.head())
print(type(df2))

df3 = df_iris[['sepal_length', 'petal_length']]  # 二维必须双括号
print(df3.head())
print(type(df3))

df4 = df_iris[1:3][['sepal_length','petal_length']]
print(df4)
print(type(df4))
原笔记输出 · 本次未执行
0    5.1
1    4.9
2    4.7
3    4.6
4    5.0
Name: sepal_length, dtype: float64
<class 'pandas.core.series.Series'>
   sepal_length
0           5.1
1           4.9
2           4.7
3           4.6
4           5.0
<class 'pandas.core.frame.DataFrame'>
   sepal_length  petal_length
0           5.1           1.4
1           4.9           1.4
2           4.7           1.3
3           4.6           1.5
4           5.0           1.4
<class 'pandas.core.frame.DataFrame'>
   sepal_length  petal_length
1           4.9           1.4
2           4.7           1.3
<class 'pandas.core.frame.DataFrame'>
PYTHON · 仅供阅读
# selection by position, use iloc, endpoint is excluded
#start index (inclusive): end index (exclusive): step
df0 = df_iris.iloc[:,3]  # ,前为行后为列
print(df0)
print(type(df0))  # Series

df1 = df_iris.iloc[:,[3]]
print(df1)
print(type(df1))  # DataFrame

df2 = df_iris.iloc[3:5,0:2]  # endpoint is excluded
print(df2)
print(type(df2))

df3 = df_iris.iloc[[1,2,4],[0,2]]
print(df3)
print(type(df3))
原笔记输出 · 本次未执行
0      0.2
1      0.2
2      0.2
3      0.2
4      0.2
      ... 
145    2.3
146    1.9
147    2.0
148    2.3
149    1.8
Name: petal_width, Length: 150, dtype: float64
<class 'pandas.core.series.Series'>
     petal_width
0            0.2
1            0.2
2            0.2
3            0.2
4            0.2
..           ...
145          2.3
146          1.9
147          2.0
148          2.3
149          1.8

[150 rows x 1 columns]
<class 'pandas.core.frame.DataFrame'>
   sepal_length  sepal_width
3           4.6          3.1
4           5.0          3.6
<class 'pandas.core.frame.DataFrame'>
   sepal_length  petal_length
1           4.9           1.4
2           4.7           1.3
4           5.0           1.4
<class 'pandas.core.frame.DataFrame'>
PYTHON · 仅供阅读
# selection by label, use loc, endpoint is included!!!
# start point (inclusive) : end point (inclusive) : step
df1 = df_iris.loc[:, ['sepal_length']]
print(df1.head())
print(type(df1))

df2 = df_iris.loc[1:3, ['sepal_length', 'petal_length']]  # endpoint is included!!!
print(df2.head())
print(type(df2))

df3 = df_iris.loc[[1, 3], 'sepal_length':'petal_length']  # endpoint is included!!!
print(df3)
原笔记输出 · 本次未执行
   sepal_length
0           5.1
1           4.9
2           4.7
3           4.6
4           5.0
<class 'pandas.core.frame.DataFrame'>
   sepal_length  petal_length
1           4.9           1.4
2           4.7           1.3
3           4.6           1.5
<class 'pandas.core.frame.DataFrame'>
   sepal_length  sepal_width  petal_length
1           4.9          3.0           1.4
3           4.6          3.1           1.5
PYTHON · 仅供阅读
# boolean masking
df1 = df_iris[(df_iris['sepal_length'] > 6.0) & (df_iris['petal_length'] < 5.0)]
print(df1)
print(type(df1))
原笔记输出 · 本次未执行
     sepal_length  sepal_width  petal_length  petal_width       class
50            7.0          3.2           4.7          1.4  versicolor
51            6.4          3.2           4.5          1.5  versicolor
52            6.9          3.1           4.9          1.5  versicolor
54            6.5          2.8           4.6          1.5  versicolor
56            6.3          3.3           4.7          1.6  versicolor
58            6.6          2.9           4.6          1.3  versicolor
63            6.1          2.9           4.7          1.4  versicolor
65            6.7          3.1           4.4          1.4  versicolor
68            6.2          2.2           4.5          1.5  versicolor
71            6.1          2.8           4.0          1.3  versicolor
72            6.3          2.5           4.9          1.5  versicolor
73            6.1          2.8           4.7          1.2  versicolor
74            6.4          2.9           4.3          1.3  versicolor
75            6.6          3.0           4.4          1.4  versicolor
76            6.8          2.8           4.8          1.4  versicolor
86            6.7          3.1           4.7          1.5  versicolor
87            6.3          2.3           4.4          1.3  versicolor
91            6.1          3.0           4.6          1.4  versicolor
97            6.2          2.9           4.3          1.3  versicolor
123           6.3          2.7           4.9          1.8   virginica
126           6.2          2.8           4.8          1.8   virginica
127           6.1          3.0           4.9          1.8   virginica
<class 'pandas.core.frame.DataFrame'>
PYTHON · 仅供阅读
(df_iris['sepal_length'] > 6.0) & (df_iris['petal_length'] < 5.0)
原笔记输出 · 本次未执行
0      False
1      False
2      False
3      False
4      False
       ...  
145    False
146    False
147    False
148    False
149    False
Length: 150, dtype: bool
PYTHON · 仅供阅读
df1 = df1.reset_index(drop=True)  # drop=False保留原有index为新一列
print(df1)
原笔记输出 · 本次未执行
    sepal_length  sepal_width  petal_length  petal_width       class
0            7.0          3.2           4.7          1.4  versicolor
1            6.4          3.2           4.5          1.5  versicolor
2            6.9          3.1           4.9          1.5  versicolor
3            6.5          2.8           4.6          1.5  versicolor
4            6.3          3.3           4.7          1.6  versicolor
5            6.6          2.9           4.6          1.3  versicolor
6            6.1          2.9           4.7          1.4  versicolor
7            6.7          3.1           4.4          1.4  versicolor
8            6.2          2.2           4.5          1.5  versicolor
9            6.1          2.8           4.0          1.3  versicolor
10           6.3          2.5           4.9          1.5  versicolor
11           6.1          2.8           4.7          1.2  versicolor
12           6.4          2.9           4.3          1.3  versicolor
13           6.6          3.0           4.4          1.4  versicolor
14           6.8          2.8           4.8          1.4  versicolor
15           6.7          3.1           4.7          1.5  versicolor
16           6.3          2.3           4.4          1.3  versicolor
17           6.1          3.0           4.6          1.4  versicolor
18           6.2          2.9           4.3          1.3  versicolor
19           6.3          2.7           4.9          1.8   virginica
20           6.2          2.8           4.8          1.8   virginica
21           6.1          3.0           4.9          1.8   virginica

(Advanced)Merging

Read this document for more info

PYTHON · 仅供阅读
# two dataframe join or concatenate
df_right=pd.DataFrame({'year':np.arange(1980,1990),'rain_cn':np.arange(800,810)})



df_right2=pd.DataFrame({'year': [1991], 'rain_cn': [800]})
PYTHON · 仅供阅读
df_right
原笔记输出 · 本次未执行
   year  rain_cn
0  1980      800
1  1981      801
2  1982      802
3  1983      803
4  1984      804
5  1985      805
6  1986      806
7  1987      807
8  1988      808
9  1989      809
PYTHON · 仅供阅读
df_right2
原笔记输出 · 本次未执行
   year  rain_cn
0  1991      800
PYTHON · 仅供阅读
df_right3=pd.concat([df_right, df_right2], ignore_index = True)
df_right3
原笔记输出 · 本次未执行
    year  rain_cn
0   1980      800
1   1981      801
2   1982      802
3   1983      803
4   1984      804
5   1985      805
6   1986      806
7   1987      807
8   1988      808
9   1989      809
10  1991      800
PYTHON · 仅供阅读
df_right2.columns = ['year', 'rain_cn1']
PYTHON · 仅供阅读
df_right2
原笔记输出 · 本次未执行
   year  rain_cn1
0  1991       800
PYTHON · 仅供阅读
df_right3=pd.concat([df_right, df_right2], ignore_index = True)
df_right3
原笔记输出 · 本次未执行
    year  rain_cn  rain_cn1
0   1980    800.0       NaN
1   1981    801.0       NaN
2   1982    802.0       NaN
3   1983    803.0       NaN
4   1984    804.0       NaN
5   1985    805.0       NaN
6   1986    806.0       NaN
7   1987    807.0       NaN
8   1988    808.0       NaN
9   1989    809.0       NaN
10  1991      NaN     800.0
PYTHON · 仅供阅读
df_right3.info()
原笔记输出 · 本次未执行
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 11 entries, 0 to 10
Data columns (total 3 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   year      11 non-null     int64  
 1   rain_cn   10 non-null     float64
 2   rain_cn1  1 non-null      float64
dtypes: float64(2), int64(1)
memory usage: 392.0 bytes
PYTHON · 仅供阅读
df_uk_rain.head(10)
原笔记输出 · 本次未执行
   water_year  rain_octsep  outflow_octsep  rain_decfeb  outflow_decfeb  \
0        1980         1182            5408          292            7248   
1        1981         1098            5112          257            7316   
2        1982         1156            5701          330            8567   
3        1983          993            4265          391            8905   
4        1984         1182            5364          217            5813   
5        1985         1027            4991          304            7951   
6        1986         1151            5196          295            7593   
7        1987         1210            5572          343            8456   
8        1988          976            4330          309            6465   
9        1989         1130            4973          470           10520   

   rain_junaug  outflow_junaug  
0          174            2212  
1          242            1936  
2          124            1802  
3          141            1078  
4          343            4313  
5          229            2595  
6          267            2826  
7          294            3154  
8          200            1440  
9          209            1740
PYTHON · 仅供阅读
df_right3.head(11)
原笔记输出 · 本次未执行
    year  rain_cn  rain_cn1
0   1980    800.0       NaN
1   1981    801.0       NaN
2   1982    802.0       NaN
3   1983    803.0       NaN
4   1984    804.0       NaN
5   1985    805.0       NaN
6   1986    806.0       NaN
7   1987    807.0       NaN
8   1988    808.0       NaN
9   1989    809.0       NaN
10  1991      NaN     800.0
PYTHON · 仅供阅读
# SQL like inner join:
df_join=pd.merge(df_uk_rain, df_right3, left_on='water_year',right_on='year',how='inner')
df_join
原笔记输出 · 本次未执行
    water_year  rain_octsep  outflow_octsep  rain_decfeb  outflow_decfeb  \
0         1980         1182            5408          292            7248   
1         1981         1098            5112          257            7316   
2         1982         1156            5701          330            8567   
3         1983          993            4265          391            8905   
4         1984         1182            5364          217            5813   
5         1985         1027            4991          304            7951   
6         1986         1151            5196          295            7593   
7         1987         1210            5572          343            8456   
8         1988          976            4330          309            6465   
9         1989         1130            4973          470           10520   
10        1991         1151            4506          246            5493   

    rain_junaug  outflow_junaug  year  rain_cn  rain_cn1  
0           174            2212  1980    800.0       NaN  
1           242            1936  1981    801.0       NaN  
2           124            1802  1982    802.0       NaN  
3           141            1078  1983    803.0       NaN  
4           343            4313  1984    804.0       NaN  
5           229            2595  1985    805.0       NaN  
6           267            2826  1986    806.0       NaN  
7           294            3154  1987    807.0       NaN  
8           200            1440  1988    808.0       NaN  
9           209            1740  1989    809.0       NaN  
10          280            2118  1991      NaN     800.0
PYTHON · 仅供阅读
#(Advanced)Review and cross reference after learning SQL
""" 
select dur.*, dr.rain_cn
from df_uk_rain dur
inner join df_right3 dr on dur.water_year = dr.year
;
"""
原笔记输出 · 本次未执行
' \nselect dur.*, dr3.rain_cn\nfrom df_uk_rain dur\ninner join df_right3 dr on dur.water_year = dr.year\n;\n'

版本说明: 上方代码含局部修正;下方/相邻输出来自原笔记运行记录(隐私字段已占位),不是本次重新运行修正版得到的结果。

(Advanced)Grouping

Read this document for more info

PYTHON · 仅供阅读
# groupby: similar to SQL groupby
df_uk_rain.groupby(df_uk_rain['water_year'] // 10 *10)[['rain_octsep','outflow_octsep','rain_decfeb']].max()
原笔记输出 · 本次未执行
            rain_octsep  outflow_octsep  rain_decfeb
water_year                                          
1980               1210            5701          470
1990               1268            5824          484
2000               1387            6391          437
2010               1285            5500          350
PYTHON · 仅供阅读
df_uk_rain['water_year'] // 10 * 10
原笔记输出 · 本次未执行
0     1980
1     1980
2     1980
3     1980
4     1980
5     1980
6     1980
7     1980
8     1980
9     1980
10    1990
11    1990
12    1990
13    1990
14    1990
15    1990
16    1990
17    1990
18    1990
19    1990
20    2000
21    2000
22    2000
23    2000
24    2000
25    2000
26    2000
27    2000
28    2000
29    2000
30    2010
31    2010
32    2010
Name: water_year, dtype: int64

Data Preprocessing

(Advanced)

  • Duplication
  • Outlier
  • Missing Value

Duplication

PYTHON · 仅供阅读
# check if a column has duplicates
df_uk_rain[df_uk_rain['rain_octsep'].duplicated(keep=False)]
原笔记输出 · 本次未执行
    water_year  rain_octsep  outflow_octsep  rain_decfeb  outflow_decfeb  \
0         1980         1182            5408          292            7248   
4         1984         1182            5364          217            5813   
6         1986         1151            5196          295            7593   
9         1989         1130            4973          470           10520   
11        1991         1151            4506          246            5493   
12        1992         1130            5246          308            8751   

    rain_junaug  outflow_junaug  
0           174            2212  
4           343            4313  
6           267            2826  
9           209            1740  
11          280            2118  
12          219            2551
PYTHON · 仅供阅读
# create a duplicated row as the last row
df_dup=df_uk_rain
df_dup_addon=df_dup.iloc[[0]]
df_dup=pd.concat([df_dup, df_dup_addon], ignore_index=True)
df_dup.iloc[[0,-1]] # first and last row
原笔记输出 · 本次未执行
    water_year  rain_octsep  outflow_octsep  rain_decfeb  outflow_decfeb  \
0         1980         1182            5408          292            7248   
33        1980         1182            5408          292            7248   

    rain_junaug  outflow_junaug  
0           174            2212  
33          174            2212
PYTHON · 仅供阅读
# check duplicate rows
df_dup[df_dup.duplicated(keep=False)]
原笔记输出 · 本次未执行
    water_year  rain_octsep  outflow_octsep  rain_decfeb  outflow_decfeb  \
0         1980         1182            5408          292            7248   
33        1980         1182            5408          292            7248   

    rain_junaug  outflow_junaug  
0           174            2212  
33          174            2212
PYTHON · 仅供阅读
# remove duplicates
df_dedup=df_dup.drop_duplicates()
df_dedup.iloc[[0,-1]]
原笔记输出 · 本次未执行
    water_year  rain_octsep  outflow_octsep  rain_decfeb  outflow_decfeb  \
0         1980         1182            5408          292            7248   
32        2012         1090            5329          350            9615   

    rain_junaug  outflow_junaug  
0           174            2212  
32          187            1797

Outlier

boxplot, winsorizing

异常点示意: 大多数观测在0附近、少量在7附近时,少数大值可能影响均值、相关系数或模型拟合。但异常不自动等于错误,先核查测量与业务含义,再考虑稳健统计或处理。

PYTHON · 仅供阅读
import seaborn as sns
# Simulate data
dt_outlier=np.concatenate([np.random.randn(1000),np.random.normal(7,1,10)])
sns.set_style('whitegrid')
sns.distplot(dt_outlier)
原笔记输出 · 已脱敏 · 本次未执行
C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\seaborn\distributions.py:2557: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
  warnings.warn(msg, FutureWarning)
原笔记输出 · 本次未执行
<AxesSubplot:ylabel='Density'>
原笔记输出 · 本次未执行
<Figure size 432x288 with 1 Axes>

输出图整理: 原图展示模拟数据分布,已改用本节的独立异常值说明:主体靠近0,另有少量来自均值7附近的观测。不是新运行的密度估计。

Outlier Detection: Boxplot

Interquartile Range(IQR): IQR= Upper Quartile(Q3) - Lower Quartile(Q1)

Lower Limit = Q1 - 1.5 IQR

Upper Limit = Q3 + 1.5 IQR

箱线图规则: 箱体从Q1到Q3,中线为中位数;IQR=Q3−Q1。常用围栏为Q1−1.5IQR和Q3+1.5IQR,围栏外点单独标示;围栏并不一定是实际须线端点。

PYTHON · 仅供阅读
sns.boxplot(dt_outlier,orient='v')  # orient:"v"|"h" 用于控制图像使水平还是竖直显示
原笔记输出 · 已脱敏 · 本次未执行
C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
  warnings.warn(
C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\seaborn\_core.py:1319: UserWarning: Vertical orientation ignored with only `x` specified.
  warnings.warn(single_var_warning.format("Vertical", "x"))
原笔记输出 · 本次未执行
<AxesSubplot:>
原笔记输出 · 本次未执行
<Figure size 432x288 with 1 Axes>

输出图整理: 箱线图用Q1/Q3与1.5IQR围栏标记候选异常点,原样本随机生成;不凭图片猜测具体分位数。

PYTHON · 仅供阅读
# define a function remove outlier using IQR
def iqr_outlier_rm(dt_input):
  lq,uq=np.percentile(dt_input,[25,75])
  lower_l=lq - 1.5*(uq-lq)
  upper_l=uq + 1.5*(uq-lq)
  return dt_input[(dt_input >= lower_l) & (dt_input <= upper_l)]
  
dt_outlier_ws=iqr_outlier_rm(dt_outlier)
sns.boxplot(dt_outlier_ws,orient='v')
原笔记输出 · 已脱敏 · 本次未执行
C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
  warnings.warn(
C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\seaborn\_core.py:1319: UserWarning: Vertical orientation ignored with only `x` specified.
  warnings.warn(single_var_warning.format("Vertical", "x"))
原笔记输出 · 本次未执行
<AxesSubplot:>
原笔记输出 · 本次未执行
<Figure size 432x288 with 1 Axes>

输出图整理: 过滤后保留围栏内观测。过滤会改变样本分布,不能因为图更整齐就认定数据更真实。

Missing Value

  • What are the missing values?

  • Why do we need to handle missing values?

    1. Data information loss.
    2. Lead to wrong prediction/classification.
    3. Sklearn machine learning models implementations do not support data with missing values.
  • How to detect missing values?

  • How to handle missing values?

    1. Elimination
    2. Imputation
PYTHON · 仅供阅读
# create a dictionary
raw_data = {'name': ['Jason', np.nan, 'Mike', 'Rayman', 'Alex', 'Meimei'], 
        'age': [36, np.nan, 36, 18, 36, 16], 
        'gender': ['m', np.nan, 'm', np.nan, 'f', 'f'], 
        'preMLScore': [1, np.nan, np.nan, 2, 3, 90],
        'postMLScore': [65, np.nan, np.nan, 62, 70, 100]}

# create a dataframe by passing a dictionary
df = pd.DataFrame(raw_data, columns = ['name', 'age', 'gender', 'preMLScore', 'postMLScore'])
PYTHON · 仅供阅读
df
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore
0   Jason  36.0      m         1.0         65.0
1     NaN   NaN    NaN         NaN          NaN
2    Mike  36.0      m         NaN          NaN
3  Rayman  18.0    NaN         2.0         62.0
4    Alex  36.0      f         3.0         70.0
5  Meimei  16.0      f        90.0        100.0
Detect missing values
PYTHON · 仅供阅读
df.info() # the overview information for the dataframe
原笔记输出 · 本次未执行
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 5 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   name         5 non-null      object 
 1   age          5 non-null      float64
 2   gender       4 non-null      object 
 3   preMLScore   4 non-null      float64
 4   postMLScore  4 non-null      float64
dtypes: float64(3), object(2)
memory usage: 368.0+ bytes
PYTHON · 仅供阅读
df.isnull()
原笔记输出 · 本次未执行
    name    age  gender  preMLScore  postMLScore
0  False  False   False       False        False
1   True   True    True        True         True
2  False  False   False        True         True
3  False  False    True       False        False
4  False  False   False       False        False
5  False  False   False       False        False
PYTHON · 仅供阅读
df.isnull().sum() # the number of rows with NaN for each column
原笔记输出 · 本次未执行
name           1
age            1
gender         2
preMLScore     2
postMLScore    2
dtype: int64
PYTHON · 仅供阅读
df.notnull().sum() # the number of rows without NaN for each column
原笔记输出 · 本次未执行
name           5
age            5
gender         4
preMLScore     4
postMLScore    4
dtype: int64
PYTHON · 仅供阅读
# axis = 1是列,一列n行,一行全是(all)NULL返回True,否则False
df.isnull().all(axis=1) # check if there is NaN row, operating on the column direction
原笔记输出 · 本次未执行
0    False
1     True
2    False
3    False
4    False
5    False
dtype: bool
PYTHON · 仅供阅读
# axis = 0是行,一行n列,一列有(any)NULL返回True,没有则返回False
df.isnull().any(axis=0) # check if there is a NaN in a column, operating on the row direction
原笔记输出 · 本次未执行
name           True
age            True
gender         True
preMLScore     True
postMLScore    True
dtype: bool
Handle Missing Values

Elimination

PYTHON · 仅供阅读
df
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore
0   Jason  36.0      m         1.0         65.0
1     NaN   NaN    NaN         NaN          NaN
2    Mike  36.0      m         NaN          NaN
3  Rayman  18.0    NaN         2.0         62.0
4    Alex  36.0      f         3.0         70.0
5  Meimei  16.0      f        90.0        100.0
PYTHON · 仅供阅读
# 这里axis=0指在行上操作
df.dropna(axis=0, how='any') # drop the rows with any NaN, equal to df.dropna(axis=0, )
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore
0   Jason  36.0      m         1.0         65.0
4    Alex  36.0      f         3.0         70.0
5  Meimei  16.0      f        90.0        100.0
PYTHON · 仅供阅读
df = df.dropna(how='all', inplace=False)  # 没给axis默认在行上操作
#df.dropna(how='all', inplace=True)  # 等价于上面df = ...
df
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore
0   Jason  36.0      m         1.0         65.0
2    Mike  36.0      m         NaN          NaN
3  Rayman  18.0    NaN         2.0         62.0
4    Alex  36.0      f         3.0         70.0
5  Meimei  16.0      f        90.0        100.0
PYTHON · 仅供阅读
df['playgames'] = np.nan # add an address column that all the values are NaN
df
原笔记输出 · 本次未执行
<ipython-input-60-57b29f6e92c3>:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['playgames'] = np.nan # add an address column that all the values are NaN
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore  playgames
0   Jason  36.0      m         1.0         65.0        NaN
2    Mike  36.0      m         NaN          NaN        NaN
3  Rayman  18.0    NaN         2.0         62.0        NaN
4    Alex  36.0      f         3.0         70.0        NaN
5  Meimei  16.0      f        90.0        100.0        NaN
PYTHON · 仅供阅读
df.dropna(axis=1, how='any') # drop columns that contain any NaN
原笔记输出 · 本次未执行
     name   age
0   Jason  36.0
2    Mike  36.0
3  Rayman  18.0
4    Alex  36.0
5  Meimei  16.0

版本说明: 上方代码含局部修正;下方/相邻输出来自原笔记运行记录(隐私字段已占位),不是本次重新运行修正版得到的结果。

PYTHON · 仅供阅读
df
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore  playgames
0   Jason  36.0      m         1.0         65.0        NaN
2    Mike  36.0      m         NaN          NaN        NaN
3  Rayman  18.0    NaN         2.0         62.0        NaN
4    Alex  36.0      f         3.0         70.0        NaN
5  Meimei  16.0      f        90.0        100.0        NaN
PYTHON · 仅供阅读
df.dropna(thresh=5) # drop the rows without at least five actual value columns
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore  playgames
0   Jason  36.0      m         1.0         65.0        NaN
4    Alex  36.0      f         3.0         70.0        NaN
5  Meimei  16.0      f        90.0        100.0        NaN

Imputation

  • Constant Value
  • Forward/Backward Fill
  • Median/Mean (numeric variables)
  • Mode (categorical variables)
PYTHON · 仅供阅读
df.fillna(0) # fill 0 to all missing values
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore  playgames
0   Jason  36.0      m         1.0         65.0        0.0
2    Mike  36.0      m         0.0          0.0        0.0
3  Rayman  18.0      0         2.0         62.0        0.0
4    Alex  36.0      f         3.0         70.0        0.0
5  Meimei  16.0      f        90.0        100.0        0.0
PYTHON · 仅供阅读
df
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore  playgames
0   Jason  36.0      m         1.0         65.0        NaN
2    Mike  36.0      m         NaN          NaN        NaN
3  Rayman  18.0    NaN         2.0         62.0        NaN
4    Alex  36.0      f         3.0         70.0        NaN
5  Meimei  16.0      f        90.0        100.0        NaN
PYTHON · 仅供阅读
df['gender'].fillna(method='ffill') # carry the forward value to the missing value
原笔记输出 · 本次未执行
0    m
2    m
3    m
4    f
5    f
Name: gender, dtype: object
PYTHON · 仅供阅读
df['gender'].fillna(method='bfill') # carry the backward value to the missing value
原笔记输出 · 本次未执行
0    m
2    m
3    f
4    f
5    f
Name: gender, dtype: object
PYTHON · 仅供阅读
df
原笔记输出 · 本次未执行
     name   age gender  preMLScore  postMLScore  playgames
0   Jason  36.0      m         1.0         65.0        NaN
2    Mike  36.0      m         NaN          NaN        NaN
3  Rayman  18.0    NaN         2.0         62.0        NaN
4    Alex  36.0      f         3.0         70.0        NaN
5  Meimei  16.0      f        90.0        100.0        NaN
PYTHON · 仅供阅读
df["preMLScore"].fillna(df["preMLScore"].median()) # fill preMLScore with its median
原笔记输出 · 本次未执行
0     1.0
2     2.5
3     2.0
4     3.0
5    90.0
Name: preMLScore, dtype: float64

整理参考资料