python删除替换dataframe中nan的方法——dropna()用法
DataFrame.dropna(axis=0,how=’any’,thresh=None,subset=None,inplace=False)
参数:
axis: 默认axis=0,0为按行删除,1为按列删除
how: 默认 ‘any’,‘any’指带缺失值的所有行/列,'all’指清除一整行/列都是缺失值的行/列
thresh: int,保留含有int个非nan值的行
subset: 删除特定列中包含缺失值的行或列
inplace: 默认False,即筛选后的数据存为副本,True表示直接在原数据上更改、
例子:
有基本dataframe
import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(24).reshape(4,6), index=[‘a’, ‘c’, ‘e’, ‘f’])
df.iloc[0,[1,2,5]]=np.nan
df.iloc[2,[1,4]]=np.nan
print(df)
结果:
现在要删除所有包含NaN的行,相当于参数全部默认
df=df.dropna()
#df=df.dropna(axis=0,how=‘any’,thresh=None,subset=None,inplace=False)
print(df)
结果:
要删除所有包含NaN的列
df=df.dropna(axis=1)
print(df)
结果:
将第二列全部设置成nan,下面都是用的下图这个DataFrame了
df.iloc[:,1]=np.nan
print(df)
结果:
删除一整列都是NaN的列
df=df.dropna(axis=1,how=‘all’)
print(df)
结果:
保留至少有3个非nan值的列
df=df.dropna(axis=1,thresh=3)
print(df)
结果:
删除列索引0,2中包含nan的行
df=df.dropna(subset=[0, 2])
print(df)
结果: