- 数据读取(带数据类型)
import pandas as pd
df=pd.read_csv('data/Missing_data_two.csv').convert_dtypes()
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 36 entries, 0 to 35
Data columns (total 6 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 编号 36 non-null Int64
1 地区 36 non-null string
2 身高 36 non-null float64
3 体重 28 non-null float64
4 年龄 27 non-null Int64
5 工资 28 non-null Int64
dtypes: Int64(3), float64(2), string(1)
memory usage: 1.9 KB
通过***convert_dtypes()***能够忽略空值对数据类型的影响,进行数据计算或者写入数据库时不用再进行数据类型的转换
3. 缺失值统计
df.isna().sum()
编号 0
地区 0
身高 0
体重 8
年龄 9
工资 8
dtype: int64
选择有空值的行
#any 至少有一个缺失值
df[df.isna().T.any()]
4. 缺失值处理
#使用前值填充
df['年龄'].fillna(method='ffill').head()
0 47
1 25
2 25
3 77
4 62
Name: 年龄, dtype: Int64
#使用后值填充
df['体重'].fillna(method='bfill').head()
0 91.80
1 91.80
2 62.18
3 59.95
4 78.42
Name: 体重, dtype: float64
#删除 subset 删除‘工资‘为空的行数据
df2=df.dropna(subset=['工资'])
df2.head()
#其它待补充:均值、0、最小值、方差等
具体缺失值处理方法需根据实际数据情况及业务需要
5. 按条件赋值(常用)
根据地区填充空值
df.loc[条件,列]
xs=(df[(df['地区']=='A') & (df['体重'].notna())]['身高']/df[(df['地区']=='A') & (df['体重'].notna())]['体重']).mean()
df.loc[df['地区']=='A','体重'].fillna(df['身高']/xs)
0 61.330405
3 59.950000
5 78.420000
7 75.420000
11 92.300000
15 64.515692
18 65.550000
21 49.170000
23 64.465070
25 57.990000
29 75.360000
33 87.000000
Name: 体重, dtype: float64
注意:多个条件时,每个条件需()并且条件之间与用’&‘或用’|’,否则报错
#错误一
df[df['地区']=='A' & df['体重'].notna()]
TypeError Traceback (most recent call last)
d:\APP\anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in na_logical_op(x, y, op)
273 # (xint or xbool) and (yint or bool)
--> 274 result = op(x, y)
275 except TypeError:
.........
TypeError: Cannot perform 'rand_' with a dtyped [bool] array and scalar of type [bool]
#错误写法二
df[(df['地区']=='A') and (df['体重'].notna())]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-56-d949835001af> in <module>
----> 1 df[(df['地区']=='A') and (df['体重'].notna())]
d:\APP\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1477 def __nonzero__(self):
1478 raise ValueError(
-> 1479 f"The truth value of a {type(self).__name__} is ambiguous. "
1480 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
1481 )
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
#正确写法
df[(df['地区']=='A') & (df['体重'].notna())]