【问题标题】:How to get a count of specific element in nested list python如何获取嵌套列表python中特定元素的计数
【发布时间】:2021-09-19 19:19:50
【问题描述】:
count_freq   data
3            [['58bcd029', 2, 'expert'], 
              ['58bcd029', 2, 'user'], 
             ['58bcd029', 2, 'expert']]
2            [['58bcd029', 2, 'expert'], 
             ['58bcd029', 2, 'expert']]
1            [['1ee429fa', 1, 'expert']]

所以我想从数据框的每一行和每个列表中获取“专家”和“用户”的计数。在统计了专家和用户之后,我想将各自的 id 存储在另一个列表中。我尝试将它们转换为字典并使用键进行计算,但它不起作用。谁能帮我做这件事?

我想要这种格式的数据框:

count_freq   count_expert  ids                     count_user ids
3            2             ['58bcd029','58bcd029'] 1          ['58bcd029']
2            2             ['58bcd029','58bcd029'] 0          []
1            1             ['1ee429fa']            0          []

【问题讨论】:

    标签: python pandas list dataframe dictionary


    【解决方案1】:

    一个解决方案可能是:

    import pandas as pd
    
    data = pd.DataFrame({
        'col': [[['58bcd029', 2, 'expert'],
                 ['58bcd029', 2, 'user'],
                 ['58bcd029', 2, 'expert']],
                [['58bcd029', 2, 'expert'],
                 ['58bcd029', 2, 'expert']],
                [['1ee429fa', 1, 'expert']]]
    })
    
    print(data)
                                                     col
    0  [[58bcd029, 2, expert], [58bcd029, 2, user], [...
    1     [[58bcd029, 2, expert], [58bcd029, 2, expert]]
    2                            [[1ee429fa, 1, expert]]
    
    
    
    data['count_expert'] = data['col'].apply(lambda x: [item for sublist in x for item in sublist].count('expert'))
    data['count_user'] = data['col'].apply(lambda x: [item for sublist in x for item in sublist].count('user'))
    data['ids_expert'] = data['col'].apply(lambda x: list(set([sublist[0] for sublist in x if sublist[2] == 'expert'])))
    data['ids_user'] = data['col'].apply(lambda x: list(set([sublist[0] for sublist in x if sublist[2] == 'user'])))
    
    
    # For the purpose of illustration, I just selected these rows, but `col` is also there.
    print(data[['count_expert', 'count_user', 'ids_expert', 'ids_user']])
    
       count_expert  count_user  ids_expert    ids_user
    0             2           1  [58bcd029]  [58bcd029]
    1             2           0  [58bcd029]          []
    2             1           0  [1ee429fa]          []
    

    【讨论】:

    • 但是如何分别获取专家和用户的ID?
    • 嗨,我已经更新了我的答案,现在看起来正确吗?
    猜你喜欢
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2015-10-15
    • 2015-03-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多