for loop to extract header for a dataframe in pandas
<p>I am a newbie in python. I have a data frame that looks like this:</p>

<pre><code>    A   B   C   D   E
0   1   0   1   0   1
1   0   1   0   0   1
2   0   1   1   1   0
3   1   0   0   1   0
4   1   0   0   1   1
</code></pre>

<p>How can I write a for loop to gather the column names for each row. I expect my result set looks like that:</p>

<pre><code>    A   B   C   D   E   Result
0   1   0   1   0   1   ACE
1   0   1   0   0   1   BE
2   0   1   1   1   0   BCD
3   1   0   0   1   0   AD
4   1   0   0   1   1   ADE
</code></pre>

<p>Anyone can help me with that? Thank you!</p>

<p>The <code>dot</code> function is done for that purpose as you want the matrix dot product between your matrix and the vector of column names:</p>

<pre><code>df.dot(df.columns)
Out[5]: 
0    ACE
1     BE
2    BCD
3     AD
4    ADE
</code></pre>

<p>If your dataframe is numeric, then obtain the boolean matrix first by test your <code>df</code> against 0:</p>

<pre><code>(df!=0).dot(df.columns)
</code></pre>

<p>PS: Just assign the result to the new column</p>

<pre><code>df['Result'] = df.dot(df.columns)

df
Out[7]: 
   A  B  C  D  E Result
0  1  0  1  0  1    ACE
1  0  1  0  0  1     BE
2  0  1  1  1  0    BCD
3  1  0  0  1  0     AD
4  1  0  0  1  1    ADE
</code></pre>

python pandas for-loop