我们日常拿到的数据,指标字段有时会混入非数字的数据,这时候会影响我们的操作,
name | height |
Hang | 180 |
Ben | 145 |
Cho | notknow |
XIn | 189 |
比如read_csv读入时,该列会以object形式读入,也不能直接进行计算,不然会出现如unsupported operand type(s) for +: 'float' and 'str'的错误
这时候就需要进行数据预处理,清除掉指标值中非数字的数据,这里我以2012_FederalElectionCommission_Database数据为例。首先读入数据,可以发现提示:Columns (6) have mixed types,这里Columns (6)是指标值混有字符串格式数据
fec = pd.read_csv('P00000001-ALL.csv')
D:\SOFTWARE\Anaconda\lib\site-packages\IPython\core\interactiveshell.py:2717: DtypeWarning: Columns (6) have mixed types. Specify dtype option on import or set low_memory=False.
interactivity=interactivity, compiler=compiler, result=result)
#先使用str打开数据
fec = pd.read_csv('P00000001-ALL.csv',dtype={'contbr_zip':str})
#然后使用str函数isdigit()判断单元格是否全为数字
fec_isnum=fec.iloc[:,6].str.isdigit()
#得到使用bool索引把全为数字的表格cleaned
cleaned = fec[fec_isnum].copy()