I have a pandas column with values ranging from 0.0 to 1.0.
I want to convert this column to a binary column (0 or 1) based on a threshold, i.e. if the value is <= threshold it will become 0 and 1 otherwise.
I have a pandas column with values ranging from 0.0 to 1.0.
I want to convert this column to a binary column (0 or 1) based on a threshold, i.e. if the value is <= threshold it will become 0 and 1 otherwise.
I would create a helper column and then iterate through the rows and setting the value for each cell. Something like this:
import pandas as pd
import numpy as np
a = np.random.random_sample(5)
df = pd.DataFrame({"A": a})
df["Helper"] = ""
for i in range(len(df)):
if df.loc[i,"A"] <= 0.5:
df.loc[i,"Helper"] = 0
else:
df.loc[i,"Helper"] = 1
Which leads to this:
A Helper
0 0.114089 0
1 0.309759 0
2 0.158169 0
3 0.444199 0
4 0.645443 1