Pandas group by, filter & plot
<p>I have a dataframe </p>

<pre><code>Date         rule_name
Jan 1 2016   A
Feb 4 2016   B
Jun 6 2016   C
Feb 5 2016   B
Feb 9 2016   D
Jun 5 2016   A
</code></pre>

<p>And so on ...</p>

<p>I am hoping to get a dataframe for each rule similar to below:
E.g. Dataframe for rule_name A:</p>

<pre><code>date       counts (rule_name)   %_rule_name 
Jan 16     1                   100
Feb 16     0                    0
Jun 16     1                   50
</code></pre>

<p>E.g Dataframe for rule_name B:</p>

<pre><code>date        counts (rule_name)   %_rule_name 
Jan 16      0                   0
Feb 16      2                   66.6
Jun 16      0                   0
</code></pre>

<p>Etc.</p>

<p>My current solution:</p>

<pre><code>rule_names = df['rule_name'].unique().tolist()
for i in rule_names:
    df_temp = df[df['rule_name'] == i]
    df_temp = df.groupby(df['date'].map(lambda x: str(x.year) + '-' + str(x.strftime('%m')))).count()
    df_temp.plot(kind='line', title = 'Rule Name: ' + str(i))
</code></pre>

<p>As you can see I am unable to get the % of rule name and am only plotting the count_rule_name.  I feel like there is (a) a solution and (b) a better solution then iterating through the each rule name and plotting but am unable to figure it out unfortunately.  </p>

<p><strong><em>Solution</em></strong><br>
Use <code>df.Date.str.split().str[0]</code> to get months</p>

<pre><code>df.groupby([df.Date.str.split().str[0]]).rule_name.value_counts(True) \
  .unstack(fill_value=0).mul(100).round(1)
</code></pre>

<p><a href="http://i.stack.imgur.com/YI8TV.png" rel="nofollow"><img src="http://i.stack.imgur.com/YI8TV.png" alt="enter image description here"></a></p>

<p><strong><em>Plot</em></strong></p>

<pre><code>df.groupby([df.Date.str.split().str[0]]).rule_name.value_counts(True) \
  .unstack(fill_value=0).mul(100).round(1).plot.bar()
</code></pre>

<p><a href="http://i.stack.imgur.com/ujd23.png" rel="nofollow"><img src="http://i.stack.imgur.com/ujd23.png" alt="enter image description here"></a></p>

<p><strong><em>Validate Counts</em></strong>  </p>

<pre><code>df.groupby([df.Date.str.split().str[0], df.rule_name]).size().unstack(fill_value=0)
</code></pre>

<p><a href="http://i.stack.imgur.com/s8nJS.png" rel="nofollow"><img src="http://i.stack.imgur.com/s8nJS.png" alt="enter image description here"></a></p>

python pandas plot group-by filtering