Plotting unique values in pandas
<p>I have a data frame where the first column is time and the second is a letter:</p>

<pre><code>Time                Letter 
2016-10-05 20:46:12 'A'
2016-10-05 20:47:12 'A'
2016-10-05 20:50:12 'B'
2016-10-06 00:46:12 'A'
2016-10-06 01:46:12 'B'
2016-10-06 01:47:12 'C'
2016-10-06 02:46:12 'D'
</code></pre>

<p>I need to group the data by hour and count number of unique letters per hour:</p>

<pre><code>Time          Unique_values
2016-10-05 20 2
2016-10-06 00 1
2016-10-06 01 2
2016-10-06 00 1

df.groupby([df.index.date,df.index.hour]).Letter.nunique().plot(kind = 'bar', rot =0)
</code></pre>

<p>provides the plot with labels like (2016-10-05,7), (2016-10-05,8)...</p>

<p>Is there any way to remove the brackets and instead of 7, 8 etc. use 07:00:00, 08:00:00?</p>

<p>You can either use pd.Grouper:</p>

<pre><code>df.groupby(pd.Grouper(key='Time', freq='H'))['Letter'].nunique()
</code></pre>

<p>Or set the time column as index and resample:</p>

<pre><code>df.set_index('Time').resample('H')['Letter'].nunique()
</code></pre>

<p>Both will fill the missing interval with zeros. Since you are plotting, I guess you'd want that. If not, you can assign the resulting Series to a variable and filter:</p>

<pre><code>ser = df.groupby(pd.Grouper(key='Time', freq='H'))['Letter'].nunique()
ser = ser[ser&gt;0]
</code></pre>

<hr>

<p>Due to a <a href="https://github.com/pydata/pandas/issues/13453" rel="nofollow">bug</a>, nunique may not work correctly in the current version. A workaround supplied there by @jcrist is to use pd.Series.nunique with agg. So you can update the above code to:</p>

<pre><code>df.groupby(pd.Grouper(key='Time', freq='H'))['Letter'].agg(pd.Series.nunique)
</code></pre>

<p>Or, </p>

<pre><code>df.set_index('Time').resample('H')['Letter'].agg(pd.Series.nunique)
</code></pre>

python pandas