Loop over multiple columns in dataframe
<p>I have a dataframe from a CSV file that has 61 columns and 1mil rows. 25 of those columns <code>(Flag_1, Flag_2, ..., Flag_25)</code> have <code>True/False</code> as values for each row of the dataframe.</p>

<p>What I'm trying to do is loop through each column to determine if there is a True for that entire row within those columns, I just need a minimum of one true. If there is a True then a new column, <code>Flag_All</code> will have a True value for that row, if not, then False.</p>

<p>I can use the for loop for a single column like so,</p>

<pre><code>for index, x in data2['FLAG_1'].iteritems() :
    data2['FLAG_ALL'] =  data2['FLAG_1'] == True
</code></pre>

<p>but can't figure out for multiple columns.  </p>

<p>Given an example dataframe of:</p>

<pre><code>df = pd.DataFrame({
    'flag_1': [False, False, True],
    'flag_2': [False, False, False],
    'flag_3': [True, False, False]})
</code></pre>

<p>You can use <code>df.filter</code> to get the appropriate columns (those starting with flag, an underscore and then digits...), then apply <code>any()</code> across the row axis to get your overall boolean column:</p>

<pre><code>df['flag_all'] = df.filter(regex='^flag_\d+$').any(axis=1)
</code></pre>

<p>Which gives you:</p>

<pre><code>  flag_1 flag_2 flag_3 flag_all
0  False  False   True     True
1  False  False  False    False
2   True  False  False     True
</code></pre>

python pandas for-loop dataframe