简体   繁体   中英

Create new dynamic dictionary from pandas dataframe

I have a dataframe that I want to take certain values from to enter into a new dictionary. I want to rename some of the columns from the dataframe and make them keys in the dictionary as well. How do I build a dynamic dictionary from scratch entering column values from my dataframe as values into the dictionary?

the df input columns include "AwardNumber" which will be "noticeNumber" in the dictionary and "College" etc. The dataframe looks like this:

AwardAmount AwardNumber         College                      Department   Name  Email  
None        3R01GM110382-03S1   College of Arts and Sciences Chemistry    Mary  mary@gsu.edu  

The desired output would be like this:

{ 
    "AwardAmount": None,
    "noticeNumber": "3R01GM110382-03S1",
    "College": "College of Arts and Sciences",
    "Department": "Chemistry",
    "Name": "Mary",
    "Email": "mary@gsu.edu"
}

Look at to_dict method. It has orient argument, which determines type of dictionary. Since, you didn't provided multiline example, I can only guess what result you want to get. Here is example with orient="records" :

df = pd.DataFrame([[None, "3R01GM110382-03S1", "College of Arts and Sciences", "Chemistry", "Mary", "mary@gsu.edu"]], columns=["AwardAmount", "AwardNumber", "College", "Department", "Name", "Email"])
(df.rename(columns={'AwardNumber': 'noticeNumber'})
   .to_dict(orient="records"))
# [{'Department': 'Chemistry', 'Name': 'Mary', 'AwardAmount': None, 'noticeNumber': '3R01GM110382-03S1', 'College': 'College of Arts and Sciences', 'Email': 'mary@gsu.edu'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM