Pandas convert pairs of values into new values

Question:

I have a pandas column that looks like this:

  gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 4
8 5
9 1

I want all the values of 1 to stay 1, 2 or 5 to become 2, and 3 or 4 to become 3. The desired output would then be

  gender
0 1
1 2
2 1
3 1
4 3
5 2
6 1
7 3
8 2
9 1

Would I just use if statements for this?

Asked By: hulio_entredas

||

Answers:

Use replace, you only need to map the values that change (5->2 and 4->3):

df['gender'] = df['gender'].replace({5: 2, 4: 3})

Output:

   gender
0       1
1       2
2       1
3       1
4       3
5       2
6       1
7       3
8       2
9       1
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.