I have a pandas dataframe and want to add a new column. For all values in 'number' which are smaller than 15 I want to add 1, for all values which are greater, 0. I tried different methods, but I don't receive the desired result.Especially, because I have problems with the structure. Here is what I wanna do:
number binary
12 1
89 0
12 1
56 0
62 0
2 1
657 0
5 1
73 0
In [6]: (df['number'] < 15).astype(int)
Out[6]:
0 1
1 0
2 1
3 0
4 0
5 1
6 0
7 1
8 0
Name: number, dtype: int32
In [7]: df['binary'] = (df['number'] < 15).astype(int)
In [8]: df
Out[8]:
number binary
0 12 1
1 89 0
2 12 1
3 56 0
4 62 0
5 2 1
6 657 0
7 5 1
8 73 0
You can convert it to boolean then multiply by 1.
import pandas as pd
df = pd.DataFrame({'number': [12, 89, 12, 56, 62, 2, 657, 5, 73]})
df['binary'] = (df.number < 15)*1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With