【问题标题】:how to convert pandas dataframe to dictionary like specified [duplicate]如何将熊猫数据框转换为指定的字典[重复]
【发布时间】:2021-11-07 16:22:28
【问题描述】:

这是数据框:

     course_id  weight
0          1      10
1          1      40
2          1      50
3          2      40
4          2      60
5          3      90
6          3      10

想把它转换成字典,比如:

{1 : [10,40,50] , 2:[40,60] , 3 :[90,10]}
df = pd.read_csv(tests) 
df = df[['course_id','weight']]
print(df)

   

【问题讨论】:

  • 分享dataframe的时候请给python代码构建,大家不用做
  • 如果我们没有没有帮助的 csv ^^ 例如粘贴 df.to_dict() 的输出

标签: python pandas


【解决方案1】:

您需要groupby course_id 列,然后保留weight,将值放入列表中,并使用to_dict() 获得最终结构

import pandas as pd

df = pd.DataFrame({'course_id': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 3},
                   'weight': {0: 10, 1: 40, 2: 50, 3: 40, 4: 60, 5: 90, 6: 10}})
result = df.groupby("course_id")['weight'].apply(list).to_dict()
print(result)  # {1: [10, 40, 50], 2: [40, 60], 3: [90, 10]}

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2020-09-08
    • 2017-11-22
    • 2019-07-18
    • 2020-12-01
    • 2018-07-14
    • 2019-05-07
    • 2023-03-10
    相关资源
    最近更新 更多