在DataFrame聚合后绘制特定列
我想画一个柱状图和折线图,显示特定的列。
我使用了 agg
函数,结果得到了和函数数量一样多的新列。如果我只想画A
列的总和和B
列的平均值,我该怎么做呢?
下面是我的代码,里面画出了所有的列。
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')
你能给我一些提示,教我怎么解决这个问题吗?谢谢你!
1 个回答
7
你有一个层级索引。所以你只需要用 tuple
的写法来选择正确的列。
所以,不要这样写:
ax = df2['A'].plot(kind="bar")
而是用:
ax = df2[('A', 'sum')].plot(kind="bar")
另外,不要这样写:
ax2.plot(ax.get_xticks(),df2['B'],marker='o')
而是用:
ax2.plot(ax.get_xticks(),df2[('B', 'mean')],marker='o')
把这些都放在一起:
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)
就能得到一个漂亮的图表:
