填写Pandas DataFrame图中的缺失值

时间:2018-08-04 20:35:50

标签: python 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

使用val这样的透视图:

# 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()

获得以下图: enter image description here

问题在于,仅填充了数据框中月份范围的值。是否可以用0填充超出范围的其余值(月)?

1 个答案:

答案 0 :(得分:3)

使用reindex-

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

reindex将插入更多行,然后fillna(0)用0填充所有na值。如果在此之后绘图,它将达到目的。

警告:所有颜色都不会清晰可见!

# 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

相关问题