Skip to main content
 首页 » 编程设计

python之使用 python 从 csv 数据集中消除不存在/空值

2024年10月24日9qlqwjy

我有以下脚本用于验证我拥有的 csv 文件,然后才能在我正在创建的 d3.js 可视化上呈现它:

import csv 
 
num_headers = 9 
 
def url_escaper(data): 
  for line in data: 
    yield line.replace('&','&') 
 
with open("adzuna_input.csv", 'r') as file_in, open("adzuna_output.csv", 'w') as file_out: 
    csv_in = csv.reader(url_escaper(file_in)) 
    csv_out = csv.writer(file_out) 
    for i, row in enumerate(csv_in): 
 
        if len(row) == num_headers: 
            csv_out.writerow(row) 
        else: 
            print "line %d is malformed" % i 

如您所见,我消除了字符 & 并用转义的 & 替换它,我尝试对空白或空值执行类似的操作,但没有成功非常有效。

我认为最好确定是否有任何列值完全由空格组成或完全为空,然后像我对太长或太短的那些格式不正确的数据一样放弃该索引.

我被困在如何执行这个需求的逻辑上,会不会是这样的

for i, row in enumerate(csv_in): 
    if i is null || whitespace: 
        print "line %d is malformed" % i 

添加

我试过这样的:

for i, row in enumerate(csv_in, starts): 
 
    if row.strip() & len(row) == num_headers: 
        csv_out.writerow(row) 
    else: 
        print "line %d is malformed" % i 

但它说 “AttributeError: 'list' object has no attribute 'strip'”

我的输入数据是这样的

http://www.edsa-project.eu/adzuna/eyJhbGciOiJIUzI1NiJ9.eyJzIjoia0EtLWlpVHhUMUNtSFM0SzE4TUVzUSIsImkiOiIzMzI2OTEyMjIifQ.qK3xtYQDxRpKJkNargPu6Jef4njm2fSZnNIVulRHoqA,Software Development Manager,Spring Technology ,Woolstone,52.042198,&,&,&,1 
http://www.edsa-project.eu/adzuna/eyJhbGciOiJIUzI1NiJ9.eyJzIjoia0EtLWlpVHhUMUNtSFM0SzE4TUVzUSIsImkiOiIzMzI4NDM1MzgifQ.pYnBX-APPdB3edTRC_M8x6usmBq_GfIxcdZOXSLJN04,Data Scientists Python R Scala Java or Matlab,Aspire Data Recruitment,    ,,,United Kingdom,data science|java|python|scala|matlab|analysis,1 

^上面的测试文件在第二个例子中包含错误——第二个记录应该被拒绝,因为有空行

请您参考如下方法:

使用strip检查列表中的任何元素是否为空:

for i, row in enumerate(csv_in, start=1): 
    if not [e for e in row if not e.strip()]: 
        if len(row) == num_headers: 
            csv_out.writerow(row) 
    else: 
        print "line %d is malformed" % i 
如果元素不为空,

strip() 将为 True。所以制作 if not e.strip() 将给出 False 的否定,即 True 我们将打印出 "行%d 格式不正确"% i

string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

示例文件,第二行为空,其下一行仅由空格组成:

test 
 
 
test 

输出:

line 2 is malformed 
line 3 is malformed 

请注意 enumerate默认从 0 开始。所以我会指定 start=1 参数以获得正确的行号。