pandas dataframe 两列转字典

在数据处理时,时常需要将数据表的两列转化为字典映射形式

df[[‘A’,‘B’]] -----> dict(key:A, value:B)

方法一:使用zip

d = dict(zip(df['A'],df['B']))
import pandas as pd
import numpy as np

test_dict = {'id':[1,2,3,4,5,6],'name':['Alice','Bob','Cindy','Eric','Helen','Grace '],'gender':[0,1,0,1,0,0],
             'math':[90,89,99,78,97,93]}
df = pd.DataFrame.from_dict(test_dict)

print(df)
'''
   id    name  gender  math
0   1   Alice       0    90
1   2     Bob       1    89
2   3   Cindy       0    99
3   4    Eric       1    78
4   5   Helen       0    97
5   6  Grace        0    93
'''

dict(zip(df['id'],df['math']))
# {1: 90, 2: 89, 3: 99, 4: 78, 5: 97, 6: 93}

方法二:将A设为索引后,转字典

d = df.set_index('A')['B'].to_dict()
d = df.set_index('id')['math'].to_dict()
# {1: 90, 2: 89, 3: 99, 4: 78, 5: 97, 6: 93}

建议使用方法二,速度更快。

实际问题中,常需要将原始表df,按某种方式聚合得到df2,需要得到df2的两列字典。可以直接联合使用 聚合groupby,agg和to_dict函数。

d = df.groupby('A')['B'].mean().to_dict()

如何得到不同性别的平均成绩字典

d = df.groupby('gender')['math'].mean().to_dict()
# {0: 94.75, 1: 83.5}

`

参考:What is the most efficient way to create a dictionary of two pandas Dataframe columns

  • 2
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值