熊猫有条件地复制单元格值

wha*_*iam 2 python pandas

使用 Pandas DataFrame,我试图将数据从一个单元格复制到另一个单元格,仅当接收方单元格包含特定值时。转移应从:

   Col1    Col2
0     4       X
1     2       5
2     1       X
3     7       8
4    12      20
5     3       X
Run Code Online (Sandbox Code Playgroud)

结果应该是

   Col1    Col2
0     4       4
1     2       5
2     1       1
3     7       8
4    12      20
5     3       3
Run Code Online (Sandbox Code Playgroud)

是否有我缺少的优雅或简单的解决方案?

Joh*_*nck 6

df.Col2 = df.Col1.where(df.Col2 == 'X', df.Col2)
Run Code Online (Sandbox Code Playgroud)