简体   繁体   English

如果不满足另一列中的条件,则尝试从 pandas 中的列返回值

[英]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.我有一个 zip 代码前缀列表,我将其与一列 zip 代码进行比较,如果它们不匹配,我将其解析为前三位以获得真/假列。 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.我有第三列包含 state 缩写、“WY”、“NY”、“KY”等,如果 zip 检查列为真,我想用“WY”替换“State”中的内容,否则,如果为假,请保留该行中已有的内容。 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:代码在这里运行良好,我在 Zip Check 中得到了正确的 True False 列,但我无法将其正确应用于下面的现有“State”列:

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:如果您不需要“ZipCheck”列而只需要定义 state,则可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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