Issue
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.
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
Answered By – enke
Answer Checked By – Mildred Charles (BugsFixing Admin)