如何按子索引对齐 Pandas 数据框列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13492530/
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
How to barplot Pandas dataframe columns aligning by sub-index?
提问by bigbug
I have a pandas dataframe dfcontains two stocks' financial ratio data :
我有一个df包含两只股票的财务比率数据的Pandas数据框:
>>> df
ROIC ROE
STK_ID RPT_Date
600141 20110331 0.012 0.022
20110630 0.031 0.063
20110930 0.048 0.103
20111231 0.063 0.122
20120331 0.017 0.033
20120630 0.032 0.077
20120930 0.050 0.120
600809 20110331 0.536 0.218
20110630 0.734 0.278
20110930 0.806 0.293
20111231 1.679 0.313
20120331 0.666 0.165
20120630 1.039 0.257
20120930 1.287 0.359
And I try to plot the ratio 'ROIC' & 'ROE' of stock '600141' & '600809' together on the same 'RPT_Date' to benchmark their performance.
我尝试在同一“RPT_Date”上绘制股票“600141”和“600809”的“ROIC”和“ROE”比率,以衡量它们的表现。
df.plot(kind='bar')gives below
df.plot(kind='bar')下面给出


The chart draws '600141' on the left side , '600809' on the right side. It is somewhat inconvenience to compare the 'ROIC' & 'ROE' of the two stocks on same report date 'RPT_Date'.
该图表在左侧绘制了“600141”,在右侧绘制了“600809”。比较同一报告日两只股票的“ROIC”和“ROE”有些不便'RPT_Date'。
What I want is to put the 'ROIC' & 'ROE' bar indexed by same 'RPT_Date' in same group side by side ( 4 bar per group), and x-axis only labels the 'RPT_Date', that will clearly tell the difference of two stocks.
我想要的是将由相同“RPT_Date”索引的“ROIC”和“ROE”条并排放在同一组中(每组 4 条),并且 x 轴仅标记“RPT_Date”,这将清楚地告诉两只股票的差价。
How to do that ?
怎么做 ?
And if I df.plot(kind='line'), it only shows two lines, but it should be four lines (2 stocks * 2 ratios) :

如果 I df.plot(kind='line'),它只显示两行,但应该是四行(2 个股票 * 2 个比率):

Is it a bug, or what I can do to correct it ? Thanks.
这是一个错误,还是我可以做些什么来纠正它?谢谢。
I am using Pandas 0.8.1.
我正在使用 Pandas 0.8.1。
回答by Wouter Overmeire
If you unstack STK_ID, you can create side by side plots per RPT_Date.
如果您取消堆叠 STK_ID,您可以创建每个 RPT_Date 的并排图。
In [55]: dfu = df.unstack("STK_ID")
In [56]: fig, axes = subplots(2,1)
In [57]: dfu.plot(ax=axes[0], kind="bar")
Out[57]: <matplotlib.axes.AxesSubplot at 0xb53070c>
In [58]: dfu.plot(ax=axes[1])
Out[58]: <matplotlib.axes.AxesSubplot at 0xb60e8cc>



