简体   繁体   中英

Replace values in multiple columns based on condition

data = {'Cat':  ['A','A','B','B','B','B'],
        'L1': ['0','0','0','0','0','0'],
        'L2': ['0','0','0','0','0','0'],
        'L3': ['0','0','0','0','0','0'],
        }

df = pd.DataFrame (data, columns = ['Cat','L1','L2','L3'])

Where 'Cat' is B, I would like to replace values in L1, L2, L3 to nan or '' .

df[['L1','L2','L3']] = np.where(df[['Cat'] == 'B', '')

the above did not work for me as I don't have y . Any suggestion?

df.loc[df.Cat == "B", "L1":"L3"] = np.nan
print(df)

Prints:

  Cat   L1   L2   L3
0   A    0    0    0
1   A    0    0    0
2   B  NaN  NaN  NaN
3   B  NaN  NaN  NaN
4   B  NaN  NaN  NaN
5   B  NaN  NaN  NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM