Python drop方法删除列之inplace参数实例
drop方法有一个可选参数inplace,表明可对原数组作出修改并返回一个新数组。不管参数默认为False还是设置为True,原数组的内存值是不会改变的,区别在于原数组的内容是否直接被修改。默认为False,表明原数组内容并不改变,如果我们需要得到改变后的内容,需要将新结果赋给一个新的数组,即data=data.drop(['test','test2'],1)。
如果将inplace值设定为True,则原数组内容直接被改变。
测试程序如下
#增加两列空值 importnumpyasnp data["test"]=np.nan data["test2"]=np.nan name gender age test2 test 0 jerry M 36 NaN NaN 1 emma F 23 NaN NaN 2 tony M 34 NaN NaN 4 bob M 20 NaN NaN #查看此时data的内存地址 id(data) 128971088 #删除这两列,inplace默认为False id(data.drop(['test','test2'],1)) 128971888 #查看data,发现数据并未改变 data name gender age test test2 0 jerry M 36 NaN NaN 1 emma F 23 NaN NaN 2 tony M 34 NaN NaN 4 bob M 20 NaN NaN #查看data的ID id(data) 128971088 #删除这两列,inplace设置为False id(data.drop(['test','test2'],1,inplace=True)) 1545984728 #查看data,数据已经改变 data name gender age test test2 0 jerry M 36 NaN NaN 1 emma F 23 NaN NaN 2 tony M 34 NaN NaN 4 bob M 20 NaN NaN #查看data的ID id(data) 128971088
补充知识:python使用del和drop方法删除DataFrame的列,使用drop方法一次删除多列
使用del和drop方法删除DataFrame中的列,使用drop方法一次删除多列
#使用del,一次只能删除一列,不能一次删除多列 #只能使用deldf['密度'],不能使用deldf[['密度','含糖率']] deldf['密度'] #deldf[['密度','含糖率']]报错 #使用drop,有三种方法: dt=dt.drop(['密度','含糖率'],axis=1)#axis=1表示删除列,['密度','含糖率']要删除的col的列表,可一次删除多列 dt.drop(['密度','含糖率'],axis=1,inplace=True)#inplace=True,直接从内部删除 dt.drop(dt.columns[[0,4,8]],axis=1,inplace=True)#dt.columns[[0,4,8]]直接使用索引查找列
以上这篇Pythondrop方法删除列之inplace参数实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。