从数据框创建字典

Creating a dictionary from a dataframe

dataframe img 我想通过创建一个字典来映射 retail_store_id 和药物名称,其中 53 即 retail_store_id 是键,值将是相应的药物名称。

dict = { '53': ['PAN 40MG TAB', 'MOXIKIND CV 625MG TAB'.....]}      

我以下面的数据集为例

您可以使用下面的代码。

import os
import  pandas as pd

# create a empty dictionary
dict = {}

# read the data from the dataframe
df = pd.read_excel(r'C:\*********\Output.xlsx')

# itterate through the DF
for index in df.index:

    # initialize key vairiable with ID columns
    key = df['ID'][index]

    # if key alreadt exists the append the value which is in list format for else starting 
    # adding values into a list
    if key in dict:
        dict[key].append(df['Medicine Name'][index])
    else:    
        dict[key] = [df['Medicine Name'][index]]


print(dict)

输出字典

{53: ['A', 'B', 'C', 'D', 'E', 'F'], 
54: ['G', 'H', 'I', 'J', 'K'], 
55: ['L', 'M']}