数据质量

1.修正有效性

审查DBPedia 数据文件autos.csv中字段"productionStartYear" 的有效性
要求:

  • check if the field "productionStartYear" contains a year
  • check if the year is in range 1886-2014
  • convert the value of the field to be just a year (not full datetime)
  • the rest of the fields and values should stay the same
  • if the value of the field is a valid year in the range as described above,
    write that line to the output_good file
  • if the value of the field is not a valid year as described above,
    write that line to the output_bad file
  • discard rows (neither write to good nor bad) if the URI is not from dbpedia.org
  • you should use the provided way of reading and writing data (DictReader and DictWriter)
import csv

INPUT_FILE = 'autos.csv'
OUTPUT_GOOD = 'autos-valid.csv'
OUTPUT_BAD = 'FIXME-autos.csv'

def process_file(input_file, output_good, output_bad):
    good_data=[]
    bad_data=[]

    with open(input_file, "r") as f:
        reader = csv.DictReader(f)
        header = reader.fieldnames
        
        for row in reader:
            if row['URI'].find('dbpedia.org')<0:
                continue
            
            ps_year=row['productionStartYear'][:4]
            try:
                ps_year=int(ps_year)
                row['productionStartYear']=ps_year
                if ps_year>=1886 and ps_year<=2014:
                    good_data.append(row)
                else:
                    bad_data.append(row)
                    
            except ValueError:
                if ps_year=='NULL':
                    bad_data.append(row)

    with open(output_good, "w") as g:
        writer = csv.DictWriter(g, delimiter=",", fieldnames= header)
        writer.writeheader()
        for row in good_data:
            writer.writerow(row)
            
    with open(output_bad, "w") as b:
        writer = csv.DictWriter(b, delimiter=",", fieldnames= header)
        writer.writeheader()
        for row in bad_data:
            writer.writerow(row)

process_file(INPUT_FILE, OUTPUT_GOOD, OUTPUT_BAD)

2.习题集

In this problem set you work with cities infobox data, audit it, come up with a
cleaning idea and then clean it up.

2.1审查数据质量

In the first exercise we want you to audit the datatypes that can be found in some particular fields in the dataset.

The possible types of values can be:

  • NoneType if the value is a string "NULL" or an empty string ""
  • list, if the value starts with "{"
  • int, if the value can be cast to int
  • float, if the value can be cast to float, but CANNOT be cast to int.
    For example, '3.23e+07' should be considered a float because it can be cast
    as float but int('3.23e+07') will throw a ValueError
  • 'str', for all other values

The audit_file function should return a dictionary containing fieldnames and a
SET of the types that can be found in the field. e.g.
{"field1": set([type(float()), type(int()), type(str())]),
"field2": set([type(str())]),
....
}
The type() function returns a type object describing the argument given to the
function. You can also use examples of objects to create type objects, e.g.
type(1.1) for a float

Note that the first three rows (after the header row) in the cities.csv file
are not actual data points. The contents of these rows should note be included
when processing data types. Be sure to include functionality in your code to
skip over or detect these rows.

import codecs
import csv
import json
import pprint

CITIES = 'cities.csv'

FIELDS = ["name", "timeZone_label", "utcOffset", "homepage", "governmentType_label",
          "isPartOf_label", "areaCode", "populationTotal", "elevation",
          "maximumElevation", "minimumElevation", "populationDensity",
          "wgs84_pos#lat", "wgs84_pos#long", "areaLand", "areaMetro", "areaUrban"]

def audit_file(filename, fields):
    fieldtypes = {field:set() for field in fields}
    
    with open(filename,'rb') as f:
        reader = csv.DictReader(f)
        
        for i in range(3):
            reader.next()
            
        for row in reader:
            for field in fields:
                
                if row[field]=='NULL' or row[field]==' ':
                    fieldtypes[field].add(type(None))
                    continue
                if row[field].startswith("{"):
                    fieldtypes[field].add(type(list()))
                    continue
                try:
                    int(row[field])
                    fieldtypes[field].add(type(int()))
                except ValueError:
                    try:
                        float(row[field])
                        fieldtypes[field].add(type(float()))
                    except ValueError:
                        fieldtypes[field].add(type(str()))


    return fieldtypes


fieldtypes = audit_file(CITIES, FIELDS)

2.2审查数据质量

“arealand”有时包含由 2 个稍有不同的值组成的数组。这个确实有点讲不通,因为一个城市的面积应该为单个值。所以,我们应该确保在我们的数据集中是这样的。但是,我们必须决定要保留哪个值。
那么我们应当保留:包含更多有效位数的值

2.3修复区域

修复字段'arealand'
Finish the function fix_area(). It will receive a string as an input, and it
has to return a float representing the value of the area or None.
修复前的字段'arealand'的值有三种类型:
1.float(可直接保留)
2.NULL(可直接保留)
3.{8.54696e+06|8.6e+06}(保留包含更多有效位数的值)

import codecs
import csv
import json
import pprint

CITIES = 'cities.csv'


def fix_area(area):
    if area=='NULL' or area==' ':
        area=None
    elif area.find("{")<0:
        area=float(area)
    elif area.find("{")==0:
        area_list=area.strip("{}").split("|")
        if len(area_list[0])>len(area_list[1]):
            area = float(area_list[0])
        else:
            area = float(area_list[1])

    return area



def process_file(filename):
    # CHANGES TO THIS FUNCTION WILL BE IGNORED WHEN YOU SUBMIT THE EXERCISE
    data = []

    with open(filename, "r") as f:
        reader = csv.DictReader(f)

        #skipping the extra metadata
        for i in range(3):
            l = reader.next()

        # processing file
        for line in reader:
            # calling your function to fix the area value
            if "areaLand" in line:
                line["areaLand"] = fix_area(line["areaLand"])
            data.append(line)

    return data

data = process_file(CITIES)

2.5修复姓名

字段“name”的值目前有三种情况:
1.null
2.单个字符串
3.{Krishnarajpet|嗖曕硟嗖粪硩嗖`舶嗖距矞嗖硣嗖熰硢}
本题处理字段“name”的值,完成函数fix_name()。它将获得字符串输入,并返回所有名称列表。如果只有一个名称,列表将只有一项。如果名称是“NULL”,该列表应该为空。

import codecs
import csv
import pprint

CITIES = 'cities.csv'


def fix_name(name):
    if name=='NULL' or name=='':
        name=[]
    elif name.find("{")<0:
        name=[name]
    elif name.find("{")==0:
        name=name.strip("{}").split("|")

    # YOUR CODE HERE

    return name


def process_file(filename):
    data = []
    with open(filename, "r") as f:
        reader = csv.DictReader(f)
        #skipping the extra metadata
        for i in range(3):
            l = reader.next()
        # processing file
        for line in reader:
            # calling your function to fix the area value
            if "name" in line:
                line["name"] = fix_name(line["name"])
            data.append(line)
    return data


data = process_file(CITIES)

2.6 交叉字段审查

如果你查看完整的城市数据,会发现有几个值似乎提供的是同一信息,只是格式不同:“point”似乎是“wgs84_pos#lat”和“wgs84_pos#long”的结合体。但是,我们不知道是否是这种情况,你应该检查它们是否相等。
Finish the function check_loc(). It will recieve 3 strings: first, the combined
value of "point" followed by the separate "wgs84_pos#" values. You have to
extract the lat and long values from the "point" argument and compare them to
the "wgs84_pos# values, returning True or False.
Note that you do not have to fix the values, only determine if they are
consistent.

import csv
import pprint

CITIES = 'cities.csv'


def check_loc(point, lat, longi):
    point_list = point.split(" ")
    if point_list[0]==lat and point_list[1]==longi:
        return True
    else:
        return False
    
    pass


def process_file(filename):
    data = []
    with open(filename, "r") as f:
        reader = csv.DictReader(f)
        #skipping the extra matadata
        for i in range(3):
            l = reader.next()
        # processing file
        for line in reader:
            # calling your function to check the location
            result = check_loc(line["point"], line["wgs84_pos#lat"], line["wgs84_pos#long"])
            if not result:
                print "{}: {} != {} {}".format(line["name"], line["point"], line["wgs84_pos#lat"], line["wgs84_pos#long"])
            data.append(line)

    return data


def test():
    assert check_loc("33.08 75.28", "33.08", "75.28") == True
    assert check_loc("44.57833333333333 -91.21833333333333", "44.5783", "-91.2183") == False

if __name__ == "__main__":
    test()
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容