0

I am looking for a way to convert column values of my dataframe to boolean values. In my dataframe below, I have columns x,y,z.

I prepared a reference dict where I got all the unique values from each column, sorted and separated by colons. Finally, I concatenated my dict with the dataframe: Here is what my dict looks like: {'x':'0:1:10','y':'5:10','z':'0:10:300'}.

Now taking these sorted dict values as a reference, I want to change my column values into binary code (as below in desired output).

My dataframe:

_______________________________
 | x | y | z |

 | 0:1:10 | 5:10 | 0:10:300 |
_______________________________
A | 0,1 | 10 | 10,300 |

B | 1 | 5 | 300,0 |

C | 10,0,1 |  | 300,10 |

________________________________

This is what my desired dataframe with binary coding looks like.

Desired output:

______________________________
 | x | y | Z |

 | 0:1:10 | 5:10 | 0:10:300 |
______________________________
A | 110 | 01 | 011 |

B | 010 | 10 | 101 |

C | 111 | 00 | 011 |
_______________________________

Thanks,Rtut

1 Answer 1

1

not sure how scalable this is, but here's one idea:

df = pd.DataFrame([["0,1", "10", "10,300"], ["1", "5", "300,0"], ["10,1,0", "", "300,10"]], columns = ["x", "y", "z"])

bin_dict_x = {'0': 100, '1': 10, '10': 1}
bin_dict_y = {'5': 10, '10': 1}
bin_dict_z = {'0': 100, '10': 10, '300': 1}

def to_bin(dct, entry):
    out = 0
    for i in entry.split(','):
       if len(i) > 0:
           out+= dct[i]  
    return str(out).zfill(len(dct))

df['x_bin'] = df.apply(lambda x: to_bin(bin_dict_x, x['x']), axis = 1)
df['y_bin'] = df.apply(lambda x: to_bin(bin_dict_y, x['y']), axis = 1)
df['z_bin'] = df.apply(lambda x: to_bin(bin_dict_y, x['z']), axis = 1)

df[['x_bin','y_bin','z_bin']]

  x_bin y_bin z_bin
0   110    01   011
1   010    10   101
2   111    00   011
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.