toceto
toceto

Reputation: 647

Transforming DataFrame to dictionary of dictionaries

I have a dataframe as follows:

df:

Employee Day Hours_Worked
Tom      Monday  5
John     Monday  2 
Tom      Tuesday 3 
John     Tuesday 4

I need to put this into a dictionary within a dictionary so that the output is like this:

print(d)

d = {'Tom':{'Monday':5, 'Tuesday':3}, 'John': {'Monday':3, 'Tuesday':4'}..}

I tried doing df.to_dict('dict') but that is not exactly what I'm looking for.

Thank you.

Upvotes: 2

Views: 351

Answers (2)

Denziloe
Denziloe

Reputation: 8162

Slightly different solution also iterating over a GroupBy:

df = pd.DataFrame(
    data = [
        ['Tom', 'Monday', 5],
        ['John', 'Monday', 2], 
        ['Tom', 'Tuesday', 3],
        ['John', 'Tuesday', 4]
    ],
    columns=['Employee', 'Day', 'Hours_Worked']
)

result = {
    employee: {row["Day"]: row["Hours_Worked"] for _, row in employee_data.iterrows()}
    for employee, employee_data in df.groupby("Employee")
}

Upvotes: 1

jpp
jpp

Reputation: 164843

You can use a dictionary comprehension with GroupBy:

res = {k: v.set_index('Day')['Hours_Worked'].to_dict() for k, v in df.groupby(['Employee'])}

# {'John': {'Monday': 2, 'Tuesday': 4}, 'Tom': {'Monday': 5, 'Tuesday': 3}}

Upvotes: 5

Related Questions