Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a column on a multi-index pandas DataFrame

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.

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?

(Sorry for not showing the df table, I don't know how to copy it correctly)

like image 567
erantdo Avatar asked Dec 13 '13 15:12

erantdo


People also ask

How do you select a column from a DataFrame by index?

Use DataFrame. loc[] and DataFrame. iloc[] to select a single column or multiple columns from pandas DataFrame by column names/label or index position respectively. where loc[] is used with column labels/names and iloc[] is used with column index/position.


1 Answers

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 = 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

like image 152
alko Avatar answered Sep 21 '22 07:09

alko