pandas,根据其他列替换数据框中的值

Shi*_*e_R 0 python dataframe pandas

我有一个如下所示的数据框,

df = pd.Dataframe({'Col1' : pd.Series(['Abc','Cde','Efg','Abc'], index=['a', 'b', 'c','d']),
 'Col2' : pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']),
 'Col3' : pd.Series([1, 2., 3., 4.], index=['a', 'b', 'c', 'd'])})
Run Code Online (Sandbox Code Playgroud)

根据Col1中列值的值,我想用Col2替换Col3值,

在这种情况下,Col1 值是“Abc”,我想用 Col2 值更新 Col3 值,期望输出如下

pd.Dataframe({'Col1' : pd.Series(['Abc','Cde','Efg','Abc'], index=['a', 'b', 'c','d']),
 'Col2' : pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']),
 'Col3' : pd.Series([10, 2., 3., 40], index=['a', 'b', 'c', 'd'])})
Run Code Online (Sandbox Code Playgroud)

通过过滤器尝试过,这不是通用的,所以任何正确的方法都可以做同样的事情!

jpp*_*jpp 5

这应该有效:

import pandas as pd

df = pd.DataFrame({'Col1' : pd.Series(['Abc','Cde','Efg','Abc'], index=['a', 'b', 'c','d']),
                   'Col2' : pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']),
                   'Col3' : pd.Series([1, 2., 3., 4.], index=['a', 'b', 'c', 'd'])})

df.loc[df['Col1'] == 'Abc', 'Col3'] = df['Col2']
Run Code Online (Sandbox Code Playgroud)