【问题标题】:Conver a Pandas Dataframe into a Dictionary of Lists, grouping by one column将 Pandas 数据框转换为列表字典,按一列分组
【发布时间】:2018-05-18 06:12:25
【问题描述】:

我有这种格式的数据:

term_x       similar_sounding_term

insurance    insurance_policy
insurance    insurance_quote
insurance    car_insurance
car rental   rental cars in Nantucket
car rental   damaged car rental policy

我想将此数据框转换为一个字典,其中键是 term_x 但值是该术语中所有关联值的列表,所以:

insurance : [insurance_policy, insurance_quote, car_insurance, rental cars in Nantucket....]

等等:

虽然here 的答案解决了我的问题,但它并没有像我希望的那样将列表合并到一个键下。

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    IIUC

    df.groupby('term_x')['similar_sounding_term'].apply(list).to_dict()
    Out[1690]: 
    {'carrental': ['rentalcarsinNantucket', 'damagedcarrentalpolicy'],
     'insurance': ['insurance_policy', 'insurance_quote', 'car_insurance']}
    

    【讨论】:

      猜你喜欢
      • 2014-06-12
      • 1970-01-01
      • 2021-11-14
      • 2021-05-02
      • 2016-05-03
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多