Binarize a float64 Pandas Dataframe in Python
<p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>

<p>for example:</p>

<pre><code>word1 word2 word3
0.0   0.3   1.0
0.1   0.0   0.5
etc
</code></pre>

<p>I want to Binarize this and instead of the frequency end up with a boolean (0s and 1s DF) that indicates the existence of a word</p>

<p>so the above example would be transformed to :</p>

<pre><code>word1 word2 word3
0      1     1
1      0     1
etc
</code></pre>

<p>I looked at get_dummies(), but the output was not the expected.</p>

<p>I would have answered as @Alberto Garcia-Raboso answered but here is an alternative that is very quick and leverages the same idea.</p>

<p>Use <code>np.where</code></p>

<pre><code>pd.DataFrame(np.where(df, 1, 0), df.index, df.columns)
</code></pre>

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

<hr>

<h1>Timing</h1>

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

python pandas dataframe