【问题标题】:How to create a pandas colum with dictionary count from another column?如何从另一列创建具有字典计数的熊猫列?
【发布时间】:2021-08-17 22:45:06
【问题描述】:

我有一个示例数据:

date        product campaign_type             total_monthly_sale
2019-01-01. Dell      [call, email, call].       5
2019-01-01. Apple     [fax, fax, visit, visit]   4
2019-02-01. Dell      [call, fax, call]          6
2019-02-01. Apple     [email, email, visit]      7

我想创建一个名为 'campaign_dict' 的新列,它给出了来自 campaign_type 列的值的计数。

示例输出如下:

date        product campaign_type             total_monthly_sale. campaign_dict
2019-01-01. Dell      [call, email, call].       5.               {'call':2,'email':1} 
2019-01-01. Apple.    [fax, fax, visit, visit].  4.               {'fax':2,'visit':2}
2019-02-01. Dell.     [call, fax, call]          6.               {'call':2,'fax':1}
2019-02-01. Apple.    [email, email, visit].     7                {'email':2,'visit':1}

【问题讨论】:

  • 是campaign_type 列表还是字符串?因为. 让我觉得它是字符串
  • 字符串列表
  • 为什么我们会在输出中看到一个点?
  • 对不起,不是点..这是一个错误

标签: python pandas dataframe numpy data-science


【解决方案1】:

试试这样的

from collections import Counter

df["campaign_dict"] = df["campaign_type"].apply(Counter)

【讨论】:

    【解决方案2】:

    您需要的是collections.Counter

    import pandas as pd
    from collections import Counter
    
    df: pd.DataFrame = pd.DataFrame([
        [["call", "email", "call"], 5],
        [["fax", "fax", "visit", "visit"], 4],
        [["call", "fax", "call"], 6],
        [["email", "email", "visit"], 7]
    ], columns=['campaign_type', 'total_monthly_sale'])
    
    df['campaign_dict'] = df['campaign_type'].apply(Counter)
    print(df) 
    
                  campaign_type  total_monthly_sale             campaign_dict
    0       [call, email, call]                   5   {'call': 2, 'email': 1}
    1  [fax, fax, visit, visit]                   4    {'fax': 2, 'visit': 2}
    2         [call, fax, call]                   6     {'call': 2, 'fax': 1}
    3     [email, email, visit]                   7  {'email': 2, 'visit': 1}
    

    【讨论】:

    • 该列是一个计数器对象,我可以将它转换为字典吗.. 我尝试做 dict(of the pandas column) 但没有正常工作。
    • @StackUser a Counter 是 dict 的子类,所以别担心你不能一样
    猜你喜欢
    • 2017-01-15
    • 2019-03-01
    • 2016-04-21
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    相关资源
    最近更新 更多