2

I've got the following pandas DataFrame :

      Month      val  count
0     1           A      1
1     1           M      1
2     2           M      2
3     3           B      3
4     3           M      5
5     5           B      1

Using pivot by val like this :

# Pivot by val
df.pivot(index='Month', columns='val',values='count').fillna(0).plot(marker='o', figsize=(14,5))

# Plot configuration
plt.title("Number of monthly searches for A, M and B")
plt.xlabel("Month")
plt.xticks(arange(12), calendar.month_abbr[1:13], rotation=45)
plt.show()

The following plot is obtained : enter image description here

The problem is that only values for the range of months in the dataframe are filled. Is it possible to fill with 0 the rest of values (months) outside the range ?

1 Answer 1

4

Use reindex -

df.pivot(index='Month', columns='val',values='count').reindex(range(1,13)).fillna(0)  

reindex will insert more rows and then fillna(0) fills all na values with 0. If you plot after that, it will do the trick.

Warning: All colors won't be distinctly visible!

# Pivot by val
df.pivot(index='Month', columns='val',values='count').reindex(range(1,13)).fillna(0).plot(marker='o', figsize=(14,5))

# Plot configuration
plt.title("Number of monthly searches for A, M and B")
plt.xlabel("Month")
plt.xticks(arange(12), calendar.month_abbr[1:13], rotation=45)
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, i've finally used reindex(arange(12)) since range(1,13) left Jan empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.