groupby 多个值,并绘制结果 [英] groupby multiple values, and plotting results

查看:36
本文介绍了groupby 多个值,并绘制结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些关于杀菌剂使用的数据,其中包含年份、杀菌剂、使用量以及熊猫数据框中的一些不相关列.看起来有点像:

年份、州、杀菌剂、价值2011 年,加利福尼亚州,A,128792011, 加利福尼亚州, B, 295722011 年,佛罗里达州,A,86452011, 佛罗里达州, B, 195732009 年,加利福尼亚州,A,87642009, 加利福尼亚州, B, 98643,...

我想要的是随时间推移使用的总杀菌剂的单一图,为每种杀菌剂绘制一条线(不同颜色).我使用 .groupby 来获取每年使用的每种杀菌剂的总量:

apple_fplot = df.groupby(['Year','Fungicide'])['Value'].sum()

这给了我想要绘制的值,例如:

年份,杀菌剂,价值...2009,甲,128635乙、1047652011年,甲,154829乙、129865

现在我需要对它进行绘图,以便每种杀菌剂(A、B、...)都是随时间变化的价值的单个绘图上的单独一行>

有没有办法在不将其全部分离的情况下做到这一点?原谅我的无知,我是python的新手,还在熟悉它.

解决方案

对于正确打印 legendxticks 的干净解决方案,您可以

apple_fplot = df.groupby(['Year','Fungicide'])['Value'].sum()plot_df = apple_fplot.unstack('杀菌剂').loc[:,'值']plot_df.index = pd.PeriodIndex(plot_df.index.tolist(), freq='A')plot_df.plot()

对于 subplots,只需将相应的 keyword 设置为 True:

plot_df.plot(subplots=True)

获得:

I'm using some data on fungicide usage which has the Year, Fungicide, Amount used, along with some irrelevant columns in a panda DataFrame. It looks somewhat like:

Year, State,      Fungicide, Value
2011, California, A,         12879
2011, California, B,         29572
2011, Florida,    A,         8645
2011, Florida,    B,         19573
2009, California, A,         8764
2009, California, B,         98643,
...

What I want from it is a single plot of total fungicide used over time, with a line plotted for each individual fungicide (in a different colour). I've used .groupby to get the total amount of each fungicide used each year:

apple_fplot = df.groupby(['Year','Fungicide'])['Value'].sum()

This gives me the values I want to plot, something like:

Year, Fungicide, Value
...
2009, A,        128635
      B,        104765
2011, A,        154829
      B,        129865

Now I need to plot it so that each fungicide (A, B, ...) is a separate line on a single plot of Value over Time

Is there a way of doing this without separating it all out? Forgive my ignorance, I'm new to python and am still getting familiar with it.

解决方案

For a clean solution that properly prints legend and xticks, you could

apple_fplot = df.groupby(['Year','Fungicide'])['Value'].sum()
plot_df = apple_fplot.unstack('Fungicide').loc[:, 'Value']
plot_df.index = pd.PeriodIndex(plot_df.index.tolist(), freq='A')
plot_df.plot()

For subplots, just set the respective keyword to True:

plot_df.plot(subplots=True)

to get:

这篇关于groupby 多个值,并绘制结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆