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>Casting to boolean will result in <code>True</code> for anything that is not zero &mdash; and <code>False</code> for any zero entry. If you then cast to integer, you get ones and zeroes.</p>

<pre><code>import io
import pandas as pd

data = io.StringIO('''\
word1 word2 word3
0.0   0.3   1.0
0.1   0.0   0.5
''')
df = pd.read_csv(data, delim_whitespace=True)

res = df.astype(bool).astype(int)
print(res)
</code></pre>

<p>Output:</p>

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

python pandas dataframe