【问题标题】:Pandas dataframe to dict, while keeping duplicate rowsPandas 数据框到 dict,同时保留重复的行
【发布时间】:2018-12-17 02:25:00
【问题描述】:

我有一个如下所示的数据框:

kenteken status code
0      XYZ      A  123
1      XYZ      B  456
2      ABC      C  789

我想将它转换为字典中的字典,如下所示:

{'XYZ':{'code':'123', 'status':'A'}, {'code':'456', 'status':'B'}, 'ABC' : {'code':'789', 'status:'C'}}

我最接近的是以下:

df.groupby('kenteken')['status', 'code'].apply(lambda x: x.to_dict()).to_dict()

产量:

{'ABC': {'status': {2: 'C'}, 'code': {2: '789'}},'XYZ': {'status': {0: 'A', 1: 'B'}, 'code': {0: '123', 1: '456'}}}

接近但不完全。我真的不知道该怎么办了,所以感谢任何帮助!

【问题讨论】:

  • 必须是字典吗?看看OrderedDict。也许元组列表足以满足您的需求。
  • 我认为这对于后面的步骤来说还不够,但我会试一试**谢谢!
  • df.to_dict(orient="records") 让你接近。
  • 字典不能有一个包含多个值的键映射,这看起来像你想要的。但是,您可以拥有一个包含多个值的元组的键。那行得通吗?一个例子是{'XYZ': ({'code':'123', 'status':'A'}, {'code':'456', 'status':'B'})}

标签: python pandas dictionary dataframe


【解决方案1】:

这对你有用吗?

a = dict(df.set_index('kenteken').groupby(level = 0).\
    apply(lambda x : x.to_dict(orient= 'records')))

打印(一)

{'ABC': [{'status': 'C', 'code': 789}], 'XYZ': [{'status': 'A', 'code': 123}, {'status': 'B', 'code': 456}]}

【讨论】:

  • 太棒了!非常感谢:D
  • 很高兴,它有帮助。顺便说一句,您也可以投票回答:D
  • 我试过了,但我的代表太低了,所以它不会明显可见(但仍然很重要);)
猜你喜欢
  • 2021-04-22
  • 2018-12-02
  • 2019-12-17
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 2019-06-05
相关资源
最近更新 更多