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'])
monthly_mean = df.resample('M', how='mean')
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?
Thanks in advance.
Also,
monthly_mean.plot(x=df.index, y='A')
monthly_mean.plot(y='A')
Uses index as x-axis by default.
Try this,
monthly_mean.plot(y='A', use_index=True)
Marius's answer worked perfectly for me:
df.reset_index() sets the index as the first column, with the column label "index." You can now use the index as an axis for plotting, as described in his answer:
monthly_mean.reset_index().plot(x='index', y='A')
However, this does not change the original dataframe. The original dataframe will be unchanged unless it is set using df = df.reset_index().
example:
df.reset_index()
print(df)
COF TSF PSF
3.0 0.946 0.914 0.966
4.0 0.963 0.940 0.976
6.0 0.978 0.965 0.987
8.0 0.989 0.984 0.995
10.0 1.000 1.000 1.000
12.0 1.004 1.013 1.009
15.0 1.013 1.026 1.012
17.0 1.019 1.037 1.017
20.0 1.024 1.045 1.020
25.0 1.030 1.057 1.026
30.0 1.034 1.065 1.030
35.0 1.037 1.069 1.031
40.0 1.037 1.068 1.030
60.0 1.037 1.068 1.030
df = df.reset_index()
print(df)
index COF TSF PSF
0 3.0 0.946 0.914 0.966
1 4.0 0.963 0.940 0.976
2 6.0 0.978 0.965 0.987
3 8.0 0.989 0.984 0.995
4 10.0 1.000 1.000 1.000
5 12.0 1.004 1.013 1.009
6 15.0 1.013 1.026 1.012
7 17.0 1.019 1.037 1.017
8 20.0 1.024 1.045 1.020
9 25.0 1.030 1.057 1.026
10 30.0 1.034 1.065 1.030
11 35.0 1.037 1.069 1.031
12 40.0 1.037 1.068 1.030
13 60.0 1.037 1.068 1.030
See: DataFrame.reset_index and DataFrame.set_index
Source: Stackoverflow.com