Pandas DataFrame缺失值的查找与填充

查看DataFrame中每一列是否存在空值:

temp = data.isnull().any() #列中是否存在空值
print(type(temp))
print(temp)

结果如下,返回结果类型是Series,列中不存在空值则对应值为False:

<class 'pandas.core.series.Series'>
eventid               False
iyear                 False
imonth                False
iday                  False
approxdate             True
extended              False
resolution             True
...
Length: 135, dtype: bool

列数太多,可以将Series转化为DataFrame不存在空值的列:

colnull=pd.DataFrame(data={'colname': temp.index,'isnulls':temp.values})
#print(colnull.head())
#不存在空值的列名
print(colnull.loc[colnull.isnulls==False,'colname'])

结果如下:

0              eventid
1                iyear
2               imonth
3                 iday
...
Name: colname, dtype: object

如下取出某一列(nkill)存在空值的记录,返回一个DataFrame:

data[data.nkill.isnull()]

缺失值填充,inplace值为真代表直接在原DataFrame上进行操作:

data['doubtterr'].fillna(0, inplace=True)
data['propvalue'].fillna(data['propvalue'].median(),inplace=True)

猜你喜欢

转载自blog.csdn.net/qq_28811329/article/details/82821971