更新时间:2023-10-25 23:28:16
Use groupby
with size
and unstack
or crosstab
alternative for reshape.
For change order of days need ordered Categorical
or reindex
by columns:
cats = ['Monday','Tuesday','Wednesday','Thursday','Friday']
df['Weekday'] = pd.Categorical(df['Weekday'], categories=cats, ordered=True)
df = df.groupby(['Time', 'Weekday']).size().unstack(fill_value=0)
df = df.groupby(['Time', 'Weekday']).size().unstack(fill_value=0).reindex(columns=cats)
Alternatives:
df = pd.crosstab(df['Time'], pd.Categorical(df['Weekday'], categories=cats, ordered=True))
df = pd.crosstab(df['Time'], df['Weekday']).reindex(columns=cats)
print (df)
col_0 Monday Tuesday Wednesday Thursday Friday
Time
21:10:00 0 1 0 0 0
21:15:00 0 1 0 0 0
21:20:00 0 2 0 0 0
21:25:00 0 0 2 0 0
21:30:00 0 0 0 0 1
21:35:00 0 0 1 1 0
21:40:00 1 0 2 0 0
Last use seaborn.heatmap
:
import seaborn as sns
sns.heatmap(df, annot=True, fmt="g", cmap='viridis')