python - Pandas Groupby 绘制按顶级分组的多重索引

标签 python pandas plot pandas-groupby multi-index

我正在努力按照我想要的方式制作 pandas groupby 多索引图。我有以下虚拟 Pandas 数据框:

data = {
    'Day': [1, 1, 2, 2, 3, 3, 4, 2, 4],
    'Condition': ['A', 'B', 'A', 'A', 'A', 'B', 'B', 'B', 'A'],
    'Invest': [1100, 2002, 500, 200, 1030, 4000, 750, 5000, 320],
    'Spent': [100, 200, 100, 100, 100, 200, 50, 300, 250]
}

index = range(len(data['Day']))

columns = ['Day', 'Condition', 'Invest', 'Spent']

df = pd.DataFrame(data, index=index, columns=columns)

+----+-------+-------------+----------+---------+
|    |   Day | Condition   |   Invest |   Spent |
|----+-------+-------------+----------+---------|
|  0 |     1 | A           |     1100 |     100 |
|  1 |     1 | B           |     2002 |     200 |
|  2 |     2 | A           |      500 |     100 |
|  3 |     2 | A           |      200 |     100 |
|  4 |     3 | A           |     1030 |     100 |
|  5 |     3 | B           |     4000 |     200 |
|  6 |     4 | B           |      750 |      50 |
|  7 |     2 | B           |     5000 |     300 |
|  8 |     4 | A           |      320 |     250 |
+----+-------+-------------+----------+---------+

我可以使用以下方法获得后续情节:

df.groupby(['Day', 'Condition']).sum()\
   .unstack()\
   .plot(subplots=True, 
    layout=(2,2),
    figsize=(8,6));

enter image description here

问题:我希望将 A 和 B 结果分组在一起。例如,顶部的图,即 (Invest, A) 和 (Invest, B) 一起在一个图中(与 Spent 类似)。因此我只有 2 个子图而不是 4 个子图。我在 stackoverflow 上有很多例子,但仍然无法使其工作。有人建议融化并使用seaborn,仍然不起作用,我更喜欢使用pandas。

PS:“顶级”是什么意思?无论我在这里是否使用正确的术语,不确定,但是当我取消堆叠分组的 Pandas 时,在 MultiIndex 中有各种级别,我的意思是根据顶层对图进行分组,如下所示:

df.groupby(['Day', 'Condition'])\
   .sum()\
   .unstack()

enter image description here

最佳答案

我会这样做:

df=df.groupby(['Day', 'Condition']).sum()\
       .unstack()

df["Invest"].plot(figsize=(8,6), title="Invest")
df["Spent"].plot(figsize=(8,6), title="Spent")

plt.show()

关于python - Pandas Groupby 绘制按顶级分组的多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56088308/

相关文章:

python - 加快 Django 表单上传大型(500k obs)CSV 文件到 MySQL 数据库

python - 属性错误 : 'PyxImporter' object has no attribute 'find_spec' with Pandas/BigQuery

python - 如何使用 python 转置和自动填充数据框?

r - 如何使用传单绘制 SpatialPolygonsDataframe 中的特定列?

python - Can't convert cuda :0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory 先

python - 如何在 Python 中的数字和文本之间放置分隔符?

python - Flask:关闭数据库连接的方式,是否能够处理高流量?

python - 在不停止部分程序的情况下在 Python 2.7 中捕获警告

python - 使用一致的映射跨数据框列分解值

matplotlib - 使用 kind reg 更改 seaborn pairplot 中的标记大小