user8034918 user8034918 - 2 months ago 40
Python Question

Decimal to Binary in Pandas

Does some one know how to separate the binary conversion of a decimal value into a csv file? I am about to convert three numbers in decimal format (3, 4, 5) to binary format and consider each zero and one as feature before applying the classifiers on the dataset. For example if we are converting '3' to binary the format would be '11'. I want to separate each one of ones in '11' from each other and consider as two features for machine learning approaches. After reading the dataset in pandas, how i can do this in python?

Answer Source

Setup:

In [179]: df = pd.DataFrame({'Col' : np.random.choice([3, 4, 5], 10)}); df
Out[179]: 
   Col
0    5
1    5
2    3
3    5
4    3
5    3
6    5
7    4
8    3
9    5

You can use df.apply and pass bin as the function:

In [180]: df.Col.apply(lambda x: pd.Series(list(bin(x)[2:]))).fillna('')
Out[180]: 
   0  1  2
0  1  0  1
1  1  0  1
2  1  1   
3  1  0  1
4  1  1   
5  1  1   
6  1  0  1
7  1  0  0
8  1  1   
9  1  0  1