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

Pandas convert pairs of values into new values

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?

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

>Solution :

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
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