title: Finding count of distinct elements in DataFrame in each column
body: <p>I am trying to find the count of distinct values in each column using Pandas. This is what I did.</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  
  # Generate data.
  NROW = 10000
  NCOL = 100
  df = pd.DataFrame(np.random.randint(1, 100000, (NROW, NCOL)),
                    columns=['col' + x for x in np.arange(NCOL).astype(str)])
  </code></pre>
  
  <p>I need to count the number of distinct elements for each column, like this:</p>
  
  <pre><code>col0    9538
  col1    9505
  col2    9524
  </code></pre>
  
  <p>What would be the most efficient way to do this, as this method will be applied to files which have size greater than 1.5GB?</p>
  
  <hr>
  
  <p>Based upon the answers, <code>df.apply(lambda x: len(x.unique()))</code> is the fastest (<a href="https://colab.research.google.com/drive/1xsrG3iUR5fkouRtBTWA2oO8YJWYqNk4G" rel="noreferrer">notebook</a>).</p>
  
  <p><code>%timeit df.apply(lambda x: len(x.unique()))
  10 loops, best of 3: 49.5 ms per loop
  %timeit df.nunique()
  10 loops, best of 3: 59.7 ms per loop
  %timeit df.apply(pd.Series.nunique)
  10 loops, best of 3: 60.3 ms per loop
  %timeit df.T.apply(lambda x: x.nunique(), axis=1)
  10 loops, best of 3: 60.5 ms per loop
  </code></p>