Home > Back-end >  Convert numbers based on value received as a parameter
Convert numbers based on value received as a parameter

Time:03-16

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:

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.

CodePudding user response:

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

CodePudding user response:

You probably forgot to change the users input into an int since it is returned as a float

data = {
        'ID' : [0, 1, 2, 3, 4, 5],
        'Match' : [0, 1, 2, 0, 0, 1]
        }
df = pd.DataFrame(data)
user_input = int(input('Enter Number to Match:'))
np.where(df['Match'] == user_input, 1, 0)
  • Related