How to turn a string column of quarterly data in pandas into sompething I can plot

Question:

I have a dataframe that looks like this:

oops:

    Quarter         London      UK          NaN
6   Mar-May 1992    0.12305     0.098332    NaN
7   Apr-Jun 1992    0.123895    0.097854    NaN
8   May-Jul 1992    0.124076    0.098878    NaN
9   Jun-Aug 1992    0.127796    0.099365    NaN
10  Jul-Sep 1992    0.126064    0.099371    NaN

I’ve tried to use the PeriodIndex on quarter so I can plot the data but it just keeps giving me errors. What can I try next?

The code that I was trying to use:

quarter_column = df.Quarter
# create PeriodIndex
periods = pd.PeriodIndex(quarter_column, freq='Q-Mar')
pd.DataFrame(df, index=periods)

The error was:

DateParseError: Unknown datetime string format, unable to parse: MAR-MAY 1992
Asked By: elksie5000

||

Answers:

Obviously PeriodIndex didn’t accept that format string. Your quarters also overlap which makes it challenging to define a PeriodIndex.

However, do you need to convert it to PeriodIndex? If your data is already sorted and indexed sequentially (6, 7, 8, 9…), you can use the code below:

# Plot the data against the dataframe's index.
# For example, the London series is actually plotted as:
# (6, 0.12305), (7, 0.123895), (8, 0.124076), ...
ax = df[["London", "UK"]].plot(marker="o")
# Tick the x-axis the same as the index, i.e: 6, 7, 8..., not 6, 6.5, 7, 7.5...
ax.xaxis.set_ticks(df.index)
# Label the ticks
ax.xaxis.set_ticklabels(df["Quarter"])

Result:

plot

Answered By: Code Different
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.