【问题标题】:How to group by one axis, count elements of another one and create a new dimension with it如何按一个轴分组,计算另一个轴的元素并用它创建一个新维度
【发布时间】:2022-11-26 21:48:48
【问题描述】:
我有以下熊猫数据框df
time animal
0 0 cat
1 0 dog
2 1 hedgehog
3 1 cat
4 1 cat
我想
- 按时间分组,同时计算动物在新组中出现的频率,例如时间 1 的 2 只猫。
- 然后为计数值创建第二个维度。
像那样:
animal cat dog hedgehog
time
0 1 1 0
1 2 0 1
任何想法如何做到这一点?
【问题讨论】:
标签:
pandas
dataframe
group-by
【解决方案1】:
试试pd.crosstab:
print(pd.crosstab(df.time, df.animal))
印刷:
animal cat dog hedgehog
time
0 1 1 0
1 2 0 1
【解决方案2】:
根据 Andrej Kesely 在他的回答中的 here,您可以使用 pandas.crosstab 计算频率表,然后,如果需要,您可以使用 seaborn.heatmap 制作热图,如下所示:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(4, 2))
sns.heatmap(pd.crosstab(df["time"], df["animal"]), annot = True)
plt.show()
# 输出 :