Home > database >  Create a nested dictionary from dataframe columns and values
Create a nested dictionary from dataframe columns and values

Time:11-17

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.

CodePudding user response:

If need nested dictionary by Name column per groups 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}}
  • Related