替换一列中的值,具体取决于另一列中的值

时间:2016-07-19 14:51:06

标签: python dictionary replace

import pandas as pd

dict = {
    '1': 'Alb',
    '2': 'Bnk',
    '3': 'Cd'
}

df = pd.DataFrame(
    {
        'col1': {
            0: 20,
            1: 2,
            2: 10,
            3: 2,
            4: 44
        }, 
        'col2': {
            0:'a',
            1:'b',
            2:'c',
            3:'b',
            4:20
        }
     }
) 

如果col1

,我想将'Bnk'值2替换为col2 value == 'b'

如何做到这一点? 感谢

1 个答案:

答案 0 :(得分:0)

有几种方法可以执行此操作,但为清楚起见,您可以使用apply

import pandas as pd

dict = {
    1: 'Alb',
    2: 'Bnk',
    3: 'Cd'
}

df = pd.DataFrame(
    {
        'col1': {
            0: 20,
            1: 2,
            2: 10,
            3: 2,
            4: 44
        }, 
        'col2': {
            0:'a',
            1:'b',
            2:'c',
            3:'b',
            4:20
        }
     }
)

def change(data, col2val, dict):
    if data['col2'] == col2val:
        data['col1'] = dict[data['col1']]

    return data

new_df = df.apply(change, axis = 1, col2val = 'b', dict = dict)

print(new_df)

为了简化起见,我还修改了dict以使其具有整数键。

输出:

  col1 col2  
0   20    a  
1  Bnk    b  
2   10    c  
3  Bnk    b  
4   44   20