【问题标题】:collections.Counter for csv file and updating blank cellscollections.Counter 用于 csv 文件和更新空白单元格
【发布时间】:2018-03-20 14:37:51
【问题描述】:

我正在从 csv 文件导入数据;并尝试确定用户类型。具体来说,我使用的是 python 模块集合。

我的数据集有空白字段,因此当我执行以下脚本 type_of_users=user_data.most_common() 时,我得到以下结果:

用户类型有:

[('Subscriber', 269149), ('Customer', 30159), ('', 692)]

有没有办法用('Unknown User Type',692) 更新('',692)

【问题讨论】:

    标签: python python-3.x counter


    【解决方案1】:

    您可以在阅读文件后对.most_common() 的结果使用列表推导:

    >>> type_of_users = [('Subscriber', 269149), ('Customer', 30159), ('', 692)]
    
    >>> type_of_users = [(i, j) if i else ('Unknown User Type', j)
    ...                  for i, j in type_of_users]
    
    >>> type_of_users
    [('Subscriber', 269149), ('Customer', 30159), ('Unknown User Type', 692)]
    

    这利用了property 将空序列 ('') 视为 False 而将非空字符串视为 True。

    请注意,还有许多其他对象也会以这种方式计算,因此如果您需要更明确,您应该使用if i != ''

    【讨论】:

    • 如果有人想知道如何将其应用于非空字符串,可以将这种情况重写为type_of_users = [(i, j) if i == '' else ('Unknown User Type', j) for i, j in type_of_users]。你可以把条件换成你需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2013-11-05
    相关资源
    最近更新 更多