Pablo Navais
Pablo Navais

Reputation: 189

Fill missing values in Pandas DataFrame plot

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 ?

Upvotes: 2

Views: 1465

Answers (1)

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

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

Upvotes: 4

Related Questions