matthew matthew - 16 days ago 6
Python Question

Binarize integer in a pandas dataframe

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

Answer
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