在多索引pandas DataFrame上选择一列

时间:2013-12-13 15:55:45

标签: python matplotlib pandas multi-index

鉴于此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)

如何绘制图表: X轴:1,2,3。 这三个系列的名字是:bar,baz,foo。 Y轴值:'一'列。 每个点旁边的标签是“两个”列。

所以,换句话说,我说有三只股票(bar,baz,& foo),每个股票的每个日期(1,2,3)都有各自的股票价格('1'),以及每个点的注释位于“两个”列。我该如何绘制图表?

(很抱歉没有显示df表,我不知道如何正确复制它)

1 个答案:

答案 0 :(得分:12)

从表格

的数据框开始
>>> 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

选择并绘制'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())

enter image description here