TNorden
TNorden

Reputation: 41

In pandas, how to plot with multiple index?

I have double index in Panda's dataframe like the example below.

           c         d
a  b         
1  3   1.519970 -0.493662
2  4   0.600178  0.274230
3  5   0.132885 -0.023688
4  6   2.410179  1.450520

How do I plot column 'c' as y-axis and index 'b' as x-axis. With one index, it is easy to plot. But I have trouble with multi index plotting. Thank you for any help!!.

Upvotes: 2

Views: 4706

Answers (1)

cs95
cs95

Reputation: 403218

Option 1
Two options have been provided (in the comments) involving reset_index. They are

df.reset_index().plot(x="b",y="c")

Or,

df.reset_index(level=0, drop=True).c.plot()

Both of these should work as expected, but will become expensive for large dataframes.


Option 2
If you are worried about memory, here's an option that does not involve resetting the index:

plt.plot(df.index.get_level_values(1), df.c)

reset_index generates copies of the data. This is more efficient, because it doesn't have to.

Upvotes: 4

Related Questions