Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas conditionally copying of cell value

Tags:

python

pandas

Working with a Pandas DataFrame, I am trying to copy data from one cell into another cell only if the recipient cell contains a specific value. The transfer should go from:

   Col1    Col2
0     4       X
1     2       5
2     1       X
3     7       8
4    12      20
5     3       X

And the result should be

   Col1    Col2
0     4       4
1     2       5
2     1       1
3     7       8
4    12      20
5     3       3

Is there an elegant or simple solution I am missing?

like image 516
whateveryousayiam Avatar asked Oct 17 '25 16:10

whateveryousayiam


2 Answers

df.Col2 = df.Col1.where(df.Col2 == 'X', df.Col2)
like image 131
John Zwinck Avatar answered Oct 19 '25 07:10

John Zwinck


import pandas as pd
import numpy as np

df.Col2 = np.where(df.Col2 == 'specific value', df.Col1, df.Col2)
like image 29
A.Kot Avatar answered Oct 19 '25 07:10

A.Kot