【问题标题】:How to remove duplicates basis keys of a csv file如何删除 csv 文件的重复基键
【发布时间】:2019-01-16 18:05:25
【问题描述】:

我有一个 csv,同时有如下图所示的数据结构:

现在我想从区域列中删除重复项,但条件是它应该是基于键的。这意味着 1 个键不能有重复的区域。区域可以在其他键中重复,但不能在同一个键中。

我正在尝试创建它,但没有得到背后的逻辑:

这些是我的代码:

import csv
OUTPUT_FILE = 'Desired_format.csv'
filename = "optionsbook.csv"
sublist = []
with open("./"+ filename, "r") as file,open(OUTPUT_FILE, 'w') as f_out:
    reader = csv.DictReader(file)
    for line in reader:
        line["key"] = line["bhk"],line["Area"],line["Property_Type"]
        if line["Area"] in line:
            continue
        else:
            sublist.append(line["key"])

【问题讨论】:

    标签: python python-3.x csv dictionary dataframe


    【解决方案1】:

    您可以使用toolz.unique。如果您无权访问此库,则可以使用 itertools 文档中相同的 unique_everseen recipe

    这是一个演示:

    from io import StringIO
    import csv
    from toolz import unique
    
    x = StringIO("""key,Area,SomeField
    12345,53.5,THIS
    12345,56.1,IS
    12345,76.0,A
    67572,35.7,MINIMAL
    67572,76.1,EXAMPLE""")
    
    # replace x with open('file.csv', 'r')
    with x as fin:
        reader = unique(csv.DictReader(fin), lambda x: x['key'])
        res = list(reader)
    
    print(res)
    
    [OrderedDict([('key', '12345'), ('Area', '53.5'), ('SomeField', 'THIS')]),
     OrderedDict([('key', '67572'), ('Area', '35.7'), ('SomeField', 'MINIMAL')])]
    

    【讨论】:

    • 哦,是的...它就是我要找的。非常感谢。
    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2015-05-24
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    相关资源
    最近更新 更多