从pandas数据框绘制一个累积图?

6

I have a dataframe as follows:

df = pd.DataFrame({'cost_saving': [10, 10, 20, 40, 60, 60],
                   'id': ['a', 'b', 'c', 'd', 'e', 'f']})

我应该如何绘制储蓄的累积图表?

我想使用一条线图,横轴为项目数量,纵轴为总储蓄金额。

这个图表应该显示大部分储蓄来自于少数几个项目。

我已经尝试过:

dftest['cost_saving'].plot(drawstyle='steps')

但它不会绘制累计值。谢谢任何帮助!

你需要添加累计和,对吧?df['cum_sum'] = df['cost_saving'].cumsum() - EdChum
实际上你的代码对我来说是可以运行的,你使用的 pandas 版本是多少?0.18.0 版本是可以正常工作的。 - EdChum
1个回答

8

我做了:

df.set_index('id').cumsum()

得到了:

    cost_saving
id             
a            10
b            20
c            40
d            80
e           140
f           200

This:

df.reset_index().plot.line(df.cost_saving.cumsum(), 'index', drawstyle='steps')

Gets me:

enter image description here


谢谢!如果我想在x轴上显示“项目数量”,而不是ID,我该怎么做? - Richard
“Number of items”是什么意思?0代表‘a’,1代表‘b’吗? - piRSquared
是的,完全正确 - 所以x轴上升到5(或6,无所谓)。 - Richard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接