2011-06-22 41 views
1

我對Python很新,我一直試圖檢測從導入的csv文件中的數據創建的列表中的缺失數據,以便我可以使用matplotlib繪製系列而不會出現錯誤。如何在Python中檢測並掩蓋導入的csv文件中的缺失數據?

我告訴你我有:

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 

我需要例如屏蔽空值'',以便我可以無誤地繪製系列。任何建議來解決這個問題?

Regards ...

回答

1

你是什麼意思的面具?去掉?如果是這樣,請嘗試以下操作:

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) 
+0

嗨,我不是故意刪除列表中的空白或缺失的數據。我需要掩蓋它,以便在使用matplotlib繪圖時相應的標記爲空。例如。如果我嘗試繪製ColOneData和ColTwoData,因爲它們現在會出現錯誤。 'plt.plot(ColOneData,ColTwoData)#這將產生一個錯誤 show()' – Jose

+0

@Jose:如果丟失的數據表示爲'0',那該怎麼辦?這是否正確繪製? –

1

何塞,如果您希望將column1繪製到column2並且沒有空項目會導致錯誤,您將不得不刪除column2中的空項目以及column1中的相應項目。像下面這樣的函數應該可以做到這一點。

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

如果你想要做什麼是填充值添加到空節點,你可以做這樣的事情:

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,等結果。

相關問題