Selecting highest rows on matrix pandas python.
<p>I have the following data:</p>

<p><a href="https://github.com/antonio1695/Python/blob/master/nearBPO/facturasb.csv" rel="nofollow">https://github.com/antonio1695/Python/blob/master/nearBPO/facturasb.csv</a></p>

<p>It is a matrix like the following example:</p>

<pre><code>UUID  A   B   C   D   E   F   G   H   I  
1.1   0   1   0   0   0   1   0   0   0
1.2   1   1   0   0   0   0   0   0   0
1.3   0   0   0   0   1   0   0   0   0
1.4   0   0   0   1   0   1   1   1   1
1.5   0   1   0   0   0   0   1   0   0
1.6   0   0   1   0   0   0   1   0   0 
1.7   0   1   0   0   0   0   0   1   0 
1.8   0   0   1   0   0   0   1   0   0
1.9   0   1   0   0   0   0   1   0   1
</code></pre>

<p>I would like to make a new matrix with only the 50 highest columns (3 in the example) and it's respective UUID. With the highest columns i mean those columns that have more 1's in the matrix. </p>

<p>If i'm not clear enough, don't hesitate asking. Thank you. </p>

<p>IIUC</p>

<pre><code>df[df.sum().nlargest(3).index]
</code></pre>

<p><a href="http://i.stack.imgur.com/V6YQi.png" rel="nofollow"><img src="http://i.stack.imgur.com/V6YQi.png" alt="enter image description here"></a></p>

<hr>

<p>To exclude rows with all zeros among the n largest</p>

<pre><code>n = df.sum().nlargest(3).index
df1 = df.loc[:, n]
df1[df1.eq(1).any(1)]
</code></pre>

<p><a href="http://i.stack.imgur.com/KAYTU.png" rel="nofollow"><img src="http://i.stack.imgur.com/KAYTU.png" alt="enter image description here"></a></p>

<hr>

<h3>Setup</h3>

<pre><code>from StringIO import StringIO
import pandas as pd

text = """UUID  A   B   C   D   E   F   G   H   I  
1.1   0   1   0   0   0   1   0   0   0
1.2   1   1   0   0   0   0   0   0   0
1.3   0   0   0   0   1   0   0   0   0
1.4   0   0   0   1   0   1   1   1   1
1.5   0   1   0   0   0   0   1   0   0
1.6   0   0   1   0   0   0   1   0   0 
1.7   0   1   0   0   0   0   0   1   0 
1.8   0   0   1   0   0   0   1   0   0
1.9   0   1   0   0   0   0   1   0   1"""

df = pd.read_csv(StringIO(text), index_col=0, delim_whitespace=True)
</code></pre>

<hr>

<h3>Bonus solution with numpy</h3>

<p>Assuming same setup (this is probably quicker)</p>

<pre><code>n = df.values.sum(0).argsort()[-3:][::-1]
m = (a[:, n] == 1).any(1)

df.iloc[m, n]
</code></pre>

<p><strong><em>Notice</em></strong> the columns are not the same as my other solution.  That is because the multiple columns summed to the same value.</p>

<p><a href="http://i.stack.imgur.com/tOeBz.png" rel="nofollow"><img src="http://i.stack.imgur.com/tOeBz.png" alt="enter image description here"></a></p>

<hr>

<h3>Timing</h3>

<p><a href="http://i.stack.imgur.com/b5Hig.png" rel="nofollow"><img src="http://i.stack.imgur.com/b5Hig.png" alt="enter image description here"></a></p>

python pandas matrix