首页 > 解决方案 > How to change a cell value of a column based on cell value of another corresponding columns

问题描述

Pasting the sample rows.

Order Number    Serial Number
318696896   Z002
319105547   Z002
319105547   Z001
319161135   Z002
319161135   Z002
319161135   Z001
319161135   Z002
319305928   Z002
319305928   Z001
319750023   Z001
319977802   Z002
319977802   Z001
319977802   Z002
320001459   Z001
320001459   Z002
320001459   Z002
320001459   Z002
320016159   Z001
320028629   Z002
320028629   Z001

e.g. 3rd row Order Number 319105547 is Z001, here I have to change the 2nd row's Serial Number from Z002 to Z001, like wise I have to do the changes for other Order Number.

标签: python-3.xpandas

解决方案


def correct_serial(df):
    serial_nos = df['Serial Number'].values
    if 'Z001' in serial_nos:
        df.loc[:, 'Serial Number'] = 'Z001'

    return df

df = df.groupby('Order Number').apply(correct_serial)

So if an Order Number has a 'Z001' Serial Number, it'll change all the Serial Number for that Order Number to 'Z001', otherwise retain what's being used.


推荐阅读