Python Pandas: Group by and count distinct value over all columns?
<p>I have df</p>

<pre><code>      column1  column2  column3  column4
0    name        True        True         NaN
1    name        NaN        True         NaN
2   name1        NaN        True         True 
3   name1        True        True       True 
</code></pre>

<p>and I would like to  Group by and count distinct value over all columnsI am trying :</p>

<pre><code>df.groupby('column1').nunique()
</code></pre>

<p>but I am receiving this error. </p>

<blockquote>
  <p>AttributeError: 'DataFrameGroupBy' object has no attribute 'nunique'</p>
</blockquote>

<p>Anybody have a suggestion?</p>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for <code>Series</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.groupby.html" rel="nofollow"><code>Series.groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>SeriesGroupBy.nunique</code></a>:</p>

<pre><code>df1 = df.set_index('column1').stack()

print (df1.groupby(level=[0,1]).nunique(dropna=False).unstack())
</code></pre>

<p>Sample:</p>

<pre><code>print (df)
  column1 column2 column3 column4
0    name    True    True     NaN
1    name     NaN    True     NaN
2   name1     NaN    True    True
3   name1    True    True    True

df1 = df.set_index('column1').stack(dropna=False)
print (df1)
column1         
name     column2    True
         column3    True
         column4     NaN
         column2     NaN
         column3    True
         column4     NaN
name1    column2     NaN
         column3    True
         column4    True
         column2    True
         column3    True
         column4    True
dtype: object

print (df1.groupby(level=[0,1]).nunique(dropna=False).unstack(fill_value=0))
         column2  column3  column4
column1                           
name           2        1        1
name1          2        1        1

print (df1.groupby(level=[0,1]).nunique().unstack(fill_value=0))
         column2  column3  column4
column1                           
name           1        1        0
name1          1        1        1
</code></pre>

<hr>

<p>Another solution with double <code>apply</code>:</p>

<pre><code>print (df.groupby('column1')
         .apply(lambda x: x.iloc[:,1:].apply(lambda y: y.nunique(dropna=False))))
         column2  column3  column4
column1                           
name           2        1        1
name1          2        1        1

print (df.groupby('column1').apply(lambda x: x.iloc[:,1:].apply(lambda y: y.nunique())))
         column2  column3  column4
column1                           
name           1        1        0
name1          1        1        1
</code></pre>

python pandas count unique distinct