Generate Series with column names of DataFrame that match condition
<p>I have a data frame with many columns containing true/false values. E. g.</p>

<pre><code>import pandas as pd
data = pd.DataFrame([[True, True, False], 
                     [False, False, True],
                     [True, False, True],
                     [False, False, False],
                     [True, True, False]], 
                    columns=['A','B','C'])
</code></pre>

<p>Actually there are many more than just those three columns.</p>

<p>I need to generate an additional column where each value is a list of the names of all columns where the value is true. For the example this should be:</p>

<pre><code>0    [A, B]
1       [C]
2    [A, C]
3        []
4    [A, B]
Name: X, dtype: object
</code></pre>

<p>Is there any magic trick in Pandas to achieve this without using nested loops (which is the only idea I had so far)?</p>

<p>You can use <code>apply</code> method to loop through rows and use each row to subset the column names:</p>

<pre><code>data.apply(lambda r: data.columns[r].tolist(), axis = 1)

#0    [A, B]
#1       [C]
#2    [A, C]
#3        []
#4    [A, B]
#dtype: object
</code></pre>

python pandas dataframe