当没有为一个或多个项目或整个单元提供信息时,可能会出现数据缺失。缺失数据在现实生活中是一个非常大的问题。缺失数据在pandas中也可以称为NA(不可用)值。在DataFrame中,有时许多数据集只是缺少数据,因为它存在而未被收集,或者它从未存在过。例如,假设被调查的不同用户可能选择不共享他们的收入,一些用户可能选择不共享地址,以这种方式许多数据集丢失。
在Pandas中,缺失数据由两个值表示:
- None:None是一个Python单例对象,通常用于Python代码中丢失的数据。
- NaN:NaN(Not a Number的首字母缩写)是一个特殊的浮点值,所有使用标准IEEE浮点表示的系统都能识别它
Pandas将None和NaN视为基本上可互换的,用于指示缺失或空值。为了方便这个约定,有几个有用的函数可以检测,删除和替换Pandas DataFrame中的null值:
isnull()
notnull()
dropna()
fillna()
replace()
interpolate()
使用isnull()和notnull()检查缺少的值
为了检查Pandas DataFrame中缺少的值,我们使用了一个函数isnull()和notnull()。这两个函数都有助于检查值是否为NaN。这些函数也可以在Pandas系列中使用,以便在系列中查找空值。
使用isnull()检查缺少的值
示例1:
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, 45, 56, np.nan],
'Third Score':[np.nan, 40, 80, 98]}
# creating a dataframe from list
df = pd.DataFrame(dict)
# using isnull() function
df.isnull()
示例2:
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# creating bool series True for NaN values
bool_series = pd.isnull(data["Gender"])
# filtering data
# displaying data only with Gender = NaN
data[bool_series]
使用notnull()检查缺少的值
为了检查Pandas Dataframe中的空值,我们使用notnull()函数,该函数返回布尔值的dataframe,对于NaN值为False。
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, 45, 56, np.nan],
'Third Score':[np.nan, 40, 80, 98]}
# creating a dataframe using dictionary
df = pd.DataFrame(dict)
# using notnull() function
df.notnull()
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# creating bool series True for NaN values
bool_series = pd.notnull(data["Gender"])
# filtering data
# displaying data only with Gender = Not NaN
data[bool_series]
使用fillna()、replace()和interpolate()填充缺失值
为了填充数据集中的空值,我们使用fillna(),replace()和interpolate()函数,这些函数将NaN值替换为它们自己的一些值。所有这些函数都有助于在DataFrame的数据集中填充空值。Interpolate()函数基本上用于填充数据中的NA值,但它使用各种插值技术来填充丢失的值,而不是硬编码值。
代码1:用单个值填充空值
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, 45, 56, np.nan],
'Third Score':[np.nan, 40, 80, 98]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
# filling missing value using fillna()
df.fillna(0)
代码2:用先前的值填充空值
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, 45, 56, np.nan],
'Third Score':[np.nan, 40, 80, 98]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
# filling a missing value with
# previous ones
df.fillna(method ='pad')
代码3:用下一个值填充空值
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, 45, 56, np.nan],
'Third Score':[np.nan, 40, 80, 98]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
# filling null value using fillna() function
df.fillna(method ='bfill')
代码4:在CSV文件中填充空值
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# Printing the first 10 to 24 rows of
# the data frame for visualization
data[10:25]
现在我们要用“No Gender”来填充性别列中的所有空值
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# filling a null values using fillna()
data["Gender"].fillna("No Gender", inplace = True)
data
代码5:使用replace()方法填充空值
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# Printing the first 10 to 24 rows of
# the data frame for visualization
data[10:25]
现在我们将数据中的所有Nan值替换为-99值。
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# will replace Nan value in dataframe with value -99
data.replace(to_replace = np.nan, value = -99)
代码6:使用interpolate()函数使用线性方法填充缺失值。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[12, 4, 5, None, 1],
"B":[None, 2, 54, 3, None],
"C":[20, 16, None, 3, 8],
"D":[14, 3, None, None, 6]})
# Print the dataframe
df
让我们使用线性方法插值缺失值。请注意,线性方法忽略索引并将值视为等间距。
# to interpolate the missing values
df.interpolate(method ='linear', limit_direction ='forward')
正如我们可以看到的输出,第一行中的值无法填充,因为值的填充方向是向前的,并且没有可以用于插值的先前值。
使用dropna()删除缺失值
为了从数据中删除空值,我们使用了dropna()函数,该函数以不同的方式删除具有空值的数据集的行/列。
代码1:删除至少包含1个null值的行。
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, np.nan, 45, 56],
'Third Score':[52, 40, 80, 98],
'Fourth Score':[np.nan, np.nan, np.nan, 65]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
df
现在我们删除至少有一个Nan值(Null值)的行
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, 90, np.nan, 95],
'Second Score': [30, np.nan, 45, 56],
'Third Score':[52, 40, 80, 98],
'Fourth Score':[np.nan, np.nan, np.nan, 65]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
# using dropna() function
df.dropna()
代码2:如果行中的所有值都丢失,则删除该行。
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
'Second Score': [30, np.nan, 45, 56],
'Third Score':[52, np.nan, 80, 98],
'Fourth Score':[np.nan, np.nan, np.nan, 65]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
df
现在我们删除所有数据缺失或包含空值(NaN)的行
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
'Second Score': [30, np.nan, 45, 56],
'Third Score':[52, np.nan, 80, 98],
'Fourth Score':[np.nan, np.nan, np.nan, 65]}
df = pd.DataFrame(dict)
# using dropna() function
df.dropna(how = 'all')
代码3:删除至少包含1个null值的列。
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
'Second Score': [30, np.nan, 45, 56],
'Third Score':[52, np.nan, 80, 98],
'Fourth Score':[60, 67, 68, 65]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
df
现在我们删除至少有1个缺失值的列
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# dictionary of lists
dict = {'First Score':[100, np.nan, np.nan, 95],
'Second Score': [30, np.nan, 45, 56],
'Third Score':[52, np.nan, 80, 98],
'Fourth Score':[60, 67, 68, 65]}
# creating a dataframe from dictionary
df = pd.DataFrame(dict)
# using dropna() function
df.dropna(axis = 1)
代码4:删除CSV文件中至少有1个空值的行
# importing pandas module
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# making new data frame with dropped NA values
new_data = data.dropna(axis = 0, how ='any')
new_data
现在我们比较数据的大小,以便了解有多少行至少有1个Null值
print("Old data frame length:", len(data))
print("New data frame length:", len(new_data))
print("Number of rows with at least 1 NA value: ", (len(data)-len(new_data)))
输出:
Old data frame length: 1000
New data frame length: 764
Number of rows with at least 1 NA value: 236
由于差值为236,因此有236行在任何列中至少有1个Null值。