[Pandas技巧] 将Dataframe转化为字典dict

[Pandas技巧] 将Dataframe转化为字典dict_第1张图片 美图欣赏2022/06/16
import pandas as pd

project_data = pd.DataFrame([['83-0382-05','Odin'],
                   ['83-0393-05','Odin PDB'],
                   ['85-0022-01','Odin REB']
                  ],columns=['Material', 'Project'])

# 将Dataframe转换成字典dict
project_dict = dict(zip(project_data['Material'],project_data['Project']))

project_data

[Pandas技巧] 将Dataframe转化为字典dict_第2张图片

project_dict

project_dict_Dictionary(3 elements)

[Pandas技巧] 将Dataframe转化为字典dict_第3张图片

project_dict字典取值 

# 1.key值查找
project_dict['83-0382-05'] # 'Odin'
project_dict['83-0393-05'] # 'Odin PDB'
project_dict['85-0022-01'] # 'Odin REB'
project_dict['86-0001-01'] # key不存在则报错 KeyError: '86-0001-01'

# 2.get()
# 语法:字典序列.get(key, 默认值)
project_dict.get('83-0382-05') # 'Odin'
project_dict.get('83-0393-05') # 'Odin PDB'
project_dict.get('85-0022-01') # 'Odin REB'
# key不存在,第二个参数不存在,返回None
print(project_dict.get('86-0001-01')) # None
# key不存在,第二个参数存在,返回第二个参数
project_dict.get('86-0001-01','The dict not this key') # 'The dict not this key'

# 3.keys()
# 语法:字典序列.keys()
# dict_keys(['83-0382-05', '83-0393-05', '85-0022-01'])
project_dict.keys() 

# 4.values()
# 语法:字典序列.values()
# dict_values(['Odin', 'Odin PDB', 'Odin REB'])
project_dict.values() 

# 5.items()
# 语法:字典序列.items()
# dict_items([('83-0382-05', 'Odin'), ('83-0393-05', 'Odin PDB'), ('85-0022-01', 'Odin REB')])
project_dict.items()

你可能感兴趣的:(Pandas,python,pandas)