【问题标题】:Convert dataframe to dictionary in Python在 Python 中将数据框转换为字典
【发布时间】:2016-10-12 14:47:41
【问题描述】:

我有一个 csv 文件,我使用 Pandas 将其转换为数据框。这是数据框:

Customer ProductID Count

John     1         50
John     2         45
Mary     1         75
Mary     2         10
Mary     5         15

我需要一个字典形式的输出,如下所示:

{ProductID:1, Count:{John:50, Mary:75}},
{ProductID:2, Count:{John:45, Mary:10}},
{ProductID:5, Count:{John:0, Mary:15}}

我阅读了以下答案:

python pandas dataframe to dictionary

Convert dataframe to dictionary

这是我的代码:

df = pd.read_csv('customer.csv') 
dict1 = df.set_index('Customer').T.to_dict('dict') 
dict2 = df.to_dict(orient='records')

这是我当前的输出:

dict1 = {'John': {'Count': 45, 'ProductID': 2}, 'Mary': {'Count': 15, 'ProductID': 5}}

dict2 = [{'Count': 50, 'Customer': 'John', 'ProductID': 1},
 {'Count': 45, 'Customer': 'John', 'ProductID': 2},
 {'Count': 75, 'Customer': 'Mary', 'ProductID': 1},
 {'Count': 10, 'Customer': 'Mary', 'ProductID': 2},
 {'Count': 15, 'Customer': 'Mary', 'ProductID': 5}]

【问题讨论】:

    标签: python dictionary pandas dataframe


    【解决方案1】:

    你可以使用的IIUC:

    d = df.groupby('ProductID').apply(lambda x: dict(zip(x.Customer, x.Count)))
          .reset_index(name='Count')
          .to_dict(orient='records')
    
    print (d)
    [{'ProductID': 1, 'Count': {'John': 50, 'Mary': 75}}, 
     {'ProductID': 2, 'Count': {'John': 45, 'Mary': 10}}, 
     {'ProductID': 5, 'Count': {'Mary': 15}}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      相关资源
      最近更新 更多