Column selection in pandas DataFrame multi-index

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 with: X axis: 1,2,3. The names of the three series: bar, baz, foo. Y axis values: one column. The label next to each dot is a two column.

So, in other words, let's say I have three stocks (bar, base and foo), each of which has its own corresponding stock price ("one") for each date (1,2,3), and a comment for each point is in column two. How to do it?

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

+6
source share
1 answer

Start with a dataframe 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 build the '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

+12
source

All Articles