pandas 在 DataFrame 聚合后绘制特定列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22210811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:46:48  来源:igfitidea点击:

Plot specific column after DataFrame aggregation

pythonmatplotlibpandas

提问by Michal

I would like to plot a bar and line graph of specific columns.

我想绘制特定列的条形图和折线图。

Using aggfunction I got as many new columns as there are functions. What can I do if I want to plot only column sum of Aand mean of Bcolumn ?

使用agg函数,我得到了与函数一样多的新列。如果我只想绘制列的总和A和列的均值,我该怎么办B

enter image description here

在此处输入图片说明

Below you can find my code, where all columns are plotted.

您可以在下面找到我的代码,其中绘制了所有列。

index=pd.date_range('2013-1-1 00:00', '2013-12-31  23:00', freq='1h')
df=pd.DataFrame(np.random.rand(len(index),2),index=index, columns=['A','B'])

df2=df.groupby(lambda x: x.month).agg({'A' : [np.mean, np.sum], 'B': np.mean}) 

fig = plt.figure()
ax = df2['A'].plot(kind="bar");plt.xticks(rotation=0)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(),df2['B'],marker='o')

Could you be able to give me some hints how to solve this ? Thank you in advance!

你能给我一些如何解决这个问题的提示吗?先感谢您!

回答by 8one6

You have a hierarchical index. So you just need to select the right columns using the tuplesyntax.

您有一个分层索引。所以你只需要使用tuple语法选择正确的列。

So instead of:

所以而不是:

ax = df2['A'].plot(kind="bar")

use:

用:

ax = df2[('A', 'sum')].plot(kind="bar")

and instead of:

而不是:

ax2.plot(ax.get_xticks(),df2['B'],marker='o')

use:

用:

ax2.plot(ax.get_xticks(),df2[('B', 'mean')],marker='o')

Putting it all together:

把它们放在一起:

import numpy as np
import pandas as pd
import seaborn as sbn
import matplotlib.pyplot as plt

np.random.seed(0)

index = pd.date_range('2013-1-1 00:00', '2013-12-31  23:00', freq='1h')
df = pd.DataFrame(np.random.rand(len(index),2),index=index, columns=['A','B'])
df2 = df.groupby(lambda x: x.month).agg({'A' : [np.mean, np.sum], 'B': np.mean}) 

fig = plt.figure()
ax = df2[('A', 'sum')].plot(kind="bar", alpha=0.7)
plt.xticks(rotation=0)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(),df2[('B', 'mean')],marker='o', c='navy', linewidth=4)

gives you a nice graph: enter image description here

给你一个漂亮的图表: 在此处输入图片说明