Pandas find first nan value by rows and return column name
<p>I have a dataframe like this </p>

<pre><code>&gt;&gt;df1 = pd.DataFrame({'A': ['1', '2', '3', '4','5'],
              'B': ['1', '1', '1', '1','1'],
              'C': ['c', 'A1', None, 'c3',None],
              'D': ['d0', 'B1', 'B2', None,'B4'],
              'E': ['A', None, 'S', None,'S'],
              'F': ['3', '4', '5', '6','7'],
              'G': ['2', '2', None, '2','2']})
&gt;&gt;df1

   A  B     C     D     E  F     G
0  1  1     c    d0     A  3     2
1  2  1    A1    B1  None  4     2
2  3  1  None    B2     S  5  None
3  4  1    c3  None  None  6     2
4  5  1  None    B4     S  7     2
</code></pre>

<p>and I drop the rows which contain nan values<code>df2 = df1.dropna()</code></p>

<pre><code>   A  B     C     D     E  F     G   
1  2  1    A1    B1  None  4     2
2  3  1  None    B2     S  5  None
3  4  1    c3  None  None  6     2
4  5  1  None    B4     S  7     2
</code></pre>

<p>This is a dropped dataframe due to those rows contain nan values.
However,I wanna know why they be dropped? Which column is the "first nan value column" made the row been dropped ? I need a dropped reason for report.</p>

<p>the output should be </p>

<pre><code>['E','C','D','C']
</code></pre>

<p>I know I can do <code>dropna</code> by each column then record it as the reason
but it's really non-efficient.</p>

<p>Is any more efficient way to solve this problem?
Thank you</p>

<p>I would use a combination of <code>itertools</code> and <code>numpy.where</code>, along with <code>pd.DataFrame.isnull</code>:</p>

<pre><code>&gt;&gt;&gt; df1.isnull()
       A      B      C      D      E      F      G
0  False  False  False  False  False  False  False
1  False  False  False  False   True  False  False
2  False  False   True  False  False  False   True
3  False  False  False   True   True  False  False
4  False  False   True  False  False  False  False
&gt;&gt;&gt; from itertools import *
&gt;&gt;&gt; r,c = np.where(df1.isnull().values)
&gt;&gt;&gt; first_cols = [next(g)[1] for _, g in groupby(izip(r,c), lambda t:t[0])]
&gt;&gt;&gt; df1.columns[first_cols]
Index([u'E', u'C', u'D', u'C'], dtype='object')
&gt;&gt;&gt; 
</code></pre>

<p>For Python 2, use <code>izip</code> from <code>itertools</code>, and in Python 3 simply use built-in <code>zip</code>. </p>

python pandas