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

Merge two columns when sign changes pandas

I would like to merge two columns into one but I am not sure how to do this efficiently. My df looks like this:

col1   col2
 0.4   -0.9
 0.2   -0.5
-0.1    0.2
-0.2    0.4
 0.8   -0.6

So if one column is positive, the other one is always negative. But I would like to have all negative numbers from column 1 replaced by all positive numbers from column 2. So it would look like this:

col1   
 0.4   
 0.2   
 0.2
 0.4
 0.8  

If you know an efficient solution to this I would really appreciate it!!

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 :

Find the rows where col1 is less than 0 and replace with col2:

df.loc[df['col1'] < 0, 'col1'] = df['col2']

result:

   col1  col2
0   0.4  -0.9
1   0.2  -0.5
2   0.2   0.2
3   0.4   0.4
4   0.8  -0.6
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