Search code examples
pythonpandasdata-visualization

Use index in pandas to plot data


I have a pandas-Dataframe and use resample() to calculate means (e.g. daily or monthly means). Here is a small example.

import pandas as pd  
import numpy as np

dates = pd.date_range('1/1/2000', periods=100)
df = pd.DataFrame(np.random.randn(100, 1), index=dates, columns=['A'])

                   A
2000-01-01 -1.210683
2000-01-02  2.242549
2000-01-03  0.801811
2000-01-04  2.353149
2000-01-05  0.359541

monthly_mean = df.resample('M').mean()

                   A
2000-01-31 -0.048088
2000-02-29 -0.094143
2000-03-31  0.126364
2000-04-30 -0.413753

How do I plot the monthly_mean now?

How do I manage to use the index of my new created DataFrame monthly_mean as the x-axis?


Solution

  • You can use reset_index to turn the index back into a column:

    monthly_mean.reset_index().plot(x='index', y='A')
    

    Look at monthly_mean.reset_index() by itself- the date is no longer in the index, but is a column in the dataframe, which is now just indexed by integers. If you look at the documentation for reset_index, you can get a bit more control over the process, including assigning sensible names to the index.