python把数据变为数据框_将数据框转换为Python中的字典

我有一个csv文件,我使用Pandas转换为数据框。这里的数据帧:将数据框转换为Python中的字典

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}}

我读了如下回答:

这是我遇到的代码:

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}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值