'Python / Pandas - How can I group a DF by two columns

I got a dataset that is built ike this:

hour weekday
12   2
14   1
12   2

and so on. I want to display in a heatmap per weekday when the dataframe had most action (which is the sum of all events that happened on that weekday during that hour)

I tried wo work with groupBy

hm = df.groupby(['hour']).sum()

which shows me all events for the hours, but does not split the events across the weekdays

How can I keep the list so I have the weekdays as an x-axis and on the y-axis the sum of the hours on that weekday?

thanks for your help!



Solution 1:[1]

The output you expect is unclear, but I imagine you could be looking for pandas.crosstab:

# computing crosstab
hm = pd.crosstab(df['hour'], df['weekday'])

# plotting heatmap
import seaborn as sns
sns.heatmap(hm, cmap='Greys')

output:

weekday  1  2
hour         
12       0  2
14       1  0

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway