Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert numbers based on value received as a parameter

For a DataFrame given below:

ID       Match     
 0           0         
 1           1          
 2           2          
 3           0           
 4           0           
 5           1                       

Using Python I want to convert all numbers of a specific value, received as a parameter, to 1 and all others to zero (and keep the correct indexing).

If the parameter is 2, the df should look this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID       Match     
 0           0         
 1           0          
 2           1          
 3           0           
 4           0           
 5           0                      

If the parameter is 0:

ID       Match     
 0           1         
 1           0          
 2           0          
 3           1           
 4           1           
 5           0                       

I tried NumPy where() and select() methods, but they ended up embarrassingly long.

>Solution :

You could use eq + astype(int):

df['Match'] = df['Match'].eq(num).astype(int)

For num=2:

   ID  Match
0   0      0
1   1      0
2   2      1
3   3      0
4   4      0
5   5      0

For num=0:

   ID  Match
0   0      1
1   1      0
2   2      0
3   3      1
4   4      1
5   5      0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading