Calculating from a pivot table using Pandas

Let's say that I have the following pivot table (this is the one created in the documentation ):

In [8]: tuples = list(zip(*[['bar', 'bar', 'baz', 'baz', ...: 'foo', 'foo', 'qux', 'qux'], ...: ['one', 'two', 'one', 'two', ...: 'one', 'two', 'one', 'two']])) ...: In [9]: index = MultiIndex.from_tuples(tuples, names=['first', 'second']) In [10]: df = DataFrame(randn(8, 2), index=index, columns=['A', 'B']) In [11]: df2 = df[:4] In [12]: df2 Out[12]: AB first second bar one 0.721555 -0.706771 two -1.039575 0.271860 baz one -0.424972 0.567020 two 0.276232 -1.087401 

How can I use this table to build a β€œbar” and β€œbase” on the same chart with axes (second, A) (i.e. I want to create a chart with points (one, 0.72), (two, -1.039), (one, -0.42), (two, 0.276), where the first two points are plotted in a different color than the last two).

I tried to use

 df2[[0]].plot() 

but this inherits the points sequentially along the x-axis, so that they are ordered ((bar, one) ,. 721), ((bar, two), -1.039), etc., and do not have two "one" points and two "two" points have a vertical axis.

+5
source share
1 answer

Ok, I figured it out. First, the key first unpacked the data:

 import matplotlib.pyplot as plt t=df2.unstack(level=0) plt.plot(t[[0]], color='red') plt.plot(t[[1]], color='blue') plt.xticks(range(2), ['one','two'], size='small') plt.show() 
+4
source

Source: https://habr.com/ru/post/1204197/


All Articles