简体   繁体   English

在多索引pandas DataFrame上选择一列

[英]Selecting a column on a multi-index pandas DataFrame

Given this DataFrame: 鉴于此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. 如何绘制图表:X轴:1,2,3。 The three series names are: bar, baz, foo. 这三个系列的名字是:bar,baz,foo。 Y-axis values: 'one' column. Y轴值:'一'列。 The label next to each dot is the 'two' column. 每个点旁边的标签是“两个”列。

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. 所以,换句话说,我说有三只股票(bar,baz,&foo),每个股票的每个日期(1,2,3)都有各自的股票价格('1'),每个股票的评论dot位于“两个”列。 How can I chart that? 我该如何绘制图表?

(Sorry for not showing the df table, I don't know how to copy it correctly) (抱歉没有显示df表,我不知道如何正确复制它)

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())

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM