如何在Python中检测和掩盖导入的csv文件中的缺失数据?
我刚开始学习Python,最近在尝试检查从导入的csv文件中创建的列表里有没有缺失的数据,这样我就可以用matplotlib来绘制图表,而不会出现错误。
我给你看看我现在的代码:
import numpy as np
# import matplotlib.pyplot as plt
import csv
from pylab import *
res = csv.reader(open('cvs_file_with_data.csv'), delimiter=',')
res.next() # do not read header
ColOneData = []
ColTwoData = []
ColThreeData = []
for col in res:
ColOneData.append(col[0])
ColTwoData.append(col[1])
ColThreeData.append(col[2])
print ColOneData # I got here the following ['1', '2', '3', '4', '5']
print ColTwoData # I got here the following ['1', '2', '', '', '5']
print ColThreeData # I got here the following ['', '', '3', '4', '']
ColTwoData_M = np.ma.masked_where(ColTwoData == '', ColTwoData) # This does not work
我需要把空值,比如说'',处理掉,这样我才能顺利绘制图表而不出错。你有什么建议可以解决这个问题吗?
谢谢!
3 个回答
1
如果你想给空的节点添加一个填充值,可以这样做:
def defaultIfEmpty(a):
if a == '':
return '0'
return a
x = ['0', '', '2', '3', '']
map (defaultIfEmpty,x)
result: x = ['0', '0', '2', '3', '0']
如果这就是你想要的结果,你可以用 map(defaultIfEmpty,ColOneData)
然后再处理 ColTwoData,等等。
1
Jose,如果你想把第一列(column1)和第二列(column2)画成图,而且不想因为第二列里面的空值出错,你需要把第二列的空值和对应的第一列的值一起去掉。下面这个函数应该可以帮你解决这个问题。
def remove_empty(col1, col2):
# make copies so our modifications don't clobber the original lists
col1 = list(col1)
col2 = list(col2)
i = 0
while i < len(col1):
# if either the item in col1 or col2 is empty remove both of them
if col1[i] == '' or col2[i] == '':
del col1[i]
del col2[i]
# otherwise, increment the index
else: i+=1
return col1, col2
1
你说的“mask”是什么意思?是要去掉吗?如果是这样,可以试试下面这个:
masked_data = [point for point in data if point != '']
补充:
我对numpy不太熟悉,但也许这就是你想要的:
>>> data = numpy.array(['0', '', '1', '', '2'])
>>> numpy.ma.masked_where(data == '', data)
masked_array(data = [0 -- 1 -- 2],
mask = [False True False True False],
fill_value = N/A)