在多索引 Pandas DataFrame 上选择一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20570626/
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
Selecting a column on a multi-index pandas DataFrame
提问by erantdo
Given this DataFrame:
鉴于此数据帧:
from pandas import DataFrame
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo'], ['one', 'two', 'one', 'two', 'one', 'two']]
tuples = zip(*arrays)
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = DataFrame(randn(3, 6), index=[1, 2, 3], columns=index)
How can I plot a chart with: X-axis: 1,2,3. The three series names are: bar, baz, foo. Y-axis values: 'one' column. The label next to each dot is the 'two' column.
如何绘制图表:X 轴:1,2,3。三个系列的名称是:bar、baz、foo。Y 轴值:“一”列。每个点旁边的标签是“二”列。
So, in other words, say I have three stocks (bar, baz, & foo), with each of them having its respective stock price ('one') for each date (1,2,3), and the comment for each dot is at the 'two' column. How can I chart that?
因此,换句话说,假设我有三只股票(bar、baz 和 foo),每只股票在每个日期(1、2、3)都有各自的股票价格(“一个”),以及每个日期的评论点位于“二”列。我怎样才能绘制它?
(Sorry for not showing the df table, I don't know how to copy it correctly)
(抱歉没有显示df表,我不知道如何正确复制)
回答by alko
Start with dataframe of form
从表单的数据框开始
>>> df
first bar baz foo
second one two one two one two
1 0.085930 -0.848468 0.911572 -0.705026 -1.284458 -0.602760
2 0.385054 2.539314 0.589164 0.765126 0.210199 -0.481789
3 -0.352475 -0.975200 -0.403591 0.975707 0.533924 -0.195430
Select and plot 'one'column
选择并绘制'one'列
>>> one = df.xs('one', level=1, axis=1)
>>> one
first bar baz foo
1 0.085930 0.911572 -1.284458
2 0.385054 0.589164 0.210199
3 -0.352475 -0.403591 0.533924
>>> pyplot.show(one.plot())



