Pandas Pivot表中缺少值?

2024-06-16 08:58:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,如下所示:

student     question                        answer   number
Bob         How many donuts in a dozen?       A        1
Sally       How many donuts in a dozen?       C        1
Edward      How many donuts in a dozen?       A        1
....
Edward      What colour is the sky?           C        1
Marvin      What colour is the sky?           D        1

从中,我编写了一些代码来生成一个透视表来汇总测试结果,如下所示:

^{pr2}$

从那里,我从透视表创建一个热图用于可视化。一般来说,这是有效的。但是,如果由于某种原因,在所选的集合中没有学生选择了其中一个答案(例如,没有人为任何问题选择“D”),那么该列就不会出现在热图中;该列被保留。在

如何确保热图中显示所有必需的列,即使没有人选择该答案?在


Tags: the数据答案iniswhatstudentmany
2条回答

你可以采取所有可能的答案和reindex你的结果。例如,在您提供的小样本中,没有学生选择B。假设你的选择是A,B,C,D:


answers = [*'ABCD']

res = df.pivot_table(
  index='question',
  columns='answer',
  values='number',
  aggfunc='sum',
  fill_value=0
).reindex(answers, axis=1, fill_value=0)

^{pr2}$


对应的热图:

import matplotlib.pyplot as plt
import seaborn as sns
sns.heatmap(res, annot=True)
plt.tight_layout()
plt.show()

enter image description here

我认为一个更简单的方法是在pivot表参数中添加'dropna=False',默认行为设置为'True'。对于我来说,这在时间序列数据中也起到了同样的作用,这些数据包含了大量与NaNs有关的天数。在

pd.pivot_table(dropna = False)

相关问题 更多 >