如何在Python中检测和屏蔽导入的csv文件中丢失的数据?

2024-10-03 21:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

我需要屏蔽空值,例如''。有什么解决这个问题的建议吗?在

问候。。。在


Tags: csvthe数据importherematplotlibrescol
3条回答

你说的面具是什么意思?删除?如果是,请尝试以下操作:

masked_data = [point for point in data if point != '']

编辑:

我不习惯裸体,但也许这就是你想要的:

^{pr2}$

如果要向空节点添加填充值,可以执行以下操作:

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)然后是coltwoadata,等等

Jose,如果你想把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

相关问题 更多 >