【问题标题】:Convert a Pandas DataFrame to a specific dictionary format将 Pandas DataFrame 转换为特定的字典格式
【发布时间】:2020-05-31 21:16:31
【问题描述】:

我有一个数据框:

Name   Fruit    Fruit-Low   Fruit-High
Joe    Apple     8.12       8.74
Joe    Pear      3.54       6.24
Jess   Orange    5.36       8.24
Jess   Apple     5.45       8.44

我正在尝试将数据框转换为特定的字典格式,例如:

dictionary = {Joe: {Apple: (8.12, 8.74), Pear: (3.54, 6.24)}, Jess: {Orange: (5.36, 8.24), Apple: (5.45, 8.44)}}

在转换数据帧时指定此格式是否需要付费?我已经尝试了 to_dict() 命令,但仍然无法像我尝试的那样引入所有行。

任何帮助将不胜感激!提前致谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为可能的解决方案是这样的,尽管我确信这不是一种讨人喜欢的方式。解决这个问题:

    def to_dict(df):
        result = {}
        for index, row in df.iterrows():
            entry = result.get(row['Name'])
            if entry == None:
                entry = {}
            entry[row['Fruit']] = (row['Fruit-Low'], row['Fruit-High'])
        return result
    

    这假设每个水果的名称都是唯一的。如果该假设错误,则解决方案将覆盖先前的条目。

    【讨论】:

      【解决方案2】:

      也许this Stack Overflow 线程可以提供帮助。你的主要方向应该是DataFrame.to_dict文档

      【讨论】:

      • 我对此进行了调查,但是无法从字典中删除列名。例如,我的输出包括字典中的 Fruit、Fruit-Low 和 Fruit-High,当我只想对有意义的值进行赋值时?
      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 2014-12-30
      • 2019-10-28
      • 2021-11-08
      • 2017-06-04
      • 2019-05-03
      相关资源
      最近更新 更多