简体   繁体   中英

Trying to return value from column in pandas if condition in another column is not met

The piece of code I am working on looks like this. I have a list of zip code prefixes I compare to a column of zip codes I parse down to the first three digits to obtain a true/false column if they match of not. I have a third column that contains the state abbreviation, 'WY', 'NY', 'KY', etc, and if the zip check column is True, I want to replace whats in 'State' with 'WY', otherwise, keep what is already in that row if false. I tried a couple of different ways and nothing wants to run.. any suggestions?

zips = ['820', '821', '822', '823', '824', '825', '826', '827', '828', '829', '830', '831']

df['Zip']= df['Zip'].astype(str)

df['ZipCheck']= df['Zip'].str[:3]

df['ZipCheck']= df['ZipCheck'].apply(lambda x: True if x in zips else False)

The code works well up to here, I get a proper True False column in Zip Check, but I cant apply it properly to the existing 'State' column below here:

df = df.assign(df['State']=np.where(df['ZipCheck'] == True, 'WY', df['State']))

If you don't need the 'ZipCheck' column but just defining the state, you can do this:

df.loc[df.Zip.str[:3].isin(zips), 'State'] = 'WY'

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