pandas group by confusion -- unhashable type
<p>Using Pandas data frame group by feature and I want to group by column <code>c_b</code> and calculate unique count for column <code>c_a</code> and column <code>c_c</code>. My expected results are,</p>

<p><strong>Expected results</strong>,</p>

<pre><code>c_b,c_a_unique_count,c_c_unique_count
python,2,2
c++,2,2
</code></pre>

<p>Met with strange error about <code>unhashable type</code>, does anyone have any ideas? Thanks.</p>

<p><strong>Input file</strong>,</p>

<pre><code>c_a,c_b,c_c,c_d
hello,python,numpy,0.0
hi,python,pandas,1.0
ho,c++,vector,0.0
ho,c++,std,1.0
go,c++,std,0.0
</code></pre>

<p><strong>Source code</strong>,</p>

<pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1,
    dtype={0:str, 1:str, 2:str, 3:float})
sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d'])
sample['c_d'] = sample['c_d'].astype('int64')
sampleGroup = sample.groupby('c_b')
results = sampleGroup.count()[:,[0,2]]
results.to_csv(derivedFeatureFile, index= False)
</code></pre>

<p><strong>Error message</strong>,</p>

<pre><code>Traceback (most recent call last):
  File "/Users/foo/personal/featureExtraction/kaggleExercise.py", line 134, in &lt;module&gt;
    unitTest()
  File "/Users/foo/personal/featureExtraction/kaggleExercise.py", line 129, in unitTest
    results = sampleGroup.count()[:,[0,2]]
  File "/Users/foo/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 1997, in __getitem__
    return self._getitem_column(key)
  File "/Users/foo/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 2004, in _getitem_column
    return self._get_item_cache(key)
  File "/Users/foo/miniconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 1348, in _get_item_cache
    res = cache.get(item)
TypeError: unhashable type
</code></pre>

<p>For the number of unique elements in each group, you can use:</p>

<pre><code>df.groupby('c_b')['c_a', 'c_d'].agg(pd.Series.nunique)
</code></pre>

<hr>

<pre><code>df.groupby('c_b')['c_a', 'c_d'].agg(pd.Series.nunique)
Out: 
        c_a  c_d
c_b             
c++       2    2
python    2    2

df.groupby('c_b', as_index=False)['c_a', 'c_d'].agg(pd.Series.nunique)
Out: 
      c_b  c_a  c_d
0     c++    2    2
1  python    2    2
</code></pre>

python python-2.7 pandas dataframe group-by