简体   繁体   中英

Create a nested dictionary from dataframe columns and values

I have a dataframe as given below

id  DateTime              Name  Status
1   02112021 02:15:00   A   FALSE
1   02112021 02:15:00   B   TRUE
2   03112021 03:00:00   A   TRUE
2   03112021 03:00:00   B   FALSE
3   03112021 03:15:00   B   FALSE

I want to create a dictionary as given below:

dict = {B : { 02112021 02:15:00 : True, 03112021 03:00:00: FALSE, 03112021 03:15:00: FALSE}}

Here, B is the key came from the column Name and Keys inside the dictionary B came from the column DateTime and its values came from Status. It will take the datetime values as key and Status values as dictionary values that corresponds to B Can anyone please help, I am stucked on it.

IIUC use:

d = df.groupby('Name')[['DateTime','Status']].apply(lambda x: dict(x.to_numpy())).to_dict()
print (d)
{'A': {'02112021 02:15:00': False, '03112021 03:00:00': True},
 'B': {'02112021 02:15:00': True, '03112021 03:00:00': False, '03112021 03:15:00': False}}

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