DataFrame:两列数据生成字典

两种方法:set_index+to_dict() ; 字典生成式

import numpy as np
import pandas as pd
num = np.random.randint(60,101,6)
data = {
    '省份':['省1','省2','省3','省4','省5','省6'],
    'num':num
}
df = pd.DataFrame(data = data)
df 
省份 num
0 省1 98
1 省2 83
2 省3 91
3 省4 84
4 省5 74
5 省6 100

方法一:通过set_index提取相应数据转化为字典

# 通过set_index提取相应数据转化为字典
dict1 = df.set_index('省份')['num'].to_dict()
dict1
{'省1': 98, '省2': 83, '省3': 91, '省4': 84, '省5': 74, '省6': 100}

方法二:字典生成表达式

# 字典生成表达式
dict2 = {row.省份 : row.num for row in df.itertuples()}
dict2
{'省1': 98, '省2': 83, '省3': 91, '省4': 84, '省5': 74, '省6': 100}

2023年11月15日更新,感谢@看见北极星 的评论
方法一下述方式也是可以实现的,结果相同

temp.set_index('省份').to_dict()['num']

你可能感兴趣的:(python数据分析总结,pandas,python,开发语言)