簡體   English   中英

與Pandas中的布爾值進行無效類型比較

[英]invalid type comparison with Booleans in Pandas

嘗試根據其他行級數據或其他具有類似數據的數據框來清理熊貓數據框(來源)中的“國家/地區”列。 請參閱鏈接,例如數據幀。

最終它將在數據框中提供兩個新列,以提供格式正確的國家/地區和數據質量“得分”。

原始數據框架 Nafta,國家和州數據框架

該函數適用於查找表或空白中的值,但是當我傳入“不良”數據時,它給出了無效的類型比較。 分別進行測試將返回一個布爾值並起作用:

Nafta.loc[Nafta[col] == a].empty .

不知道為什么這行不通。 我已經測試了值及其對Boolan的布爾值。 請參閱自定義函數和lambda。

def CountryScore(a,b,c): 
    if pd.isnull(a):
        score = "blank"
        if pd.notnull(b):
            for col in States:
                if States.loc[States[col]== b].empty != True:
                    corfor = States.iloc[States.loc[States[col] == b].index[-1],2]
                    break
                else:
                    corfor = "Bad Data"
                    continue
        elif pd.notnull(c):
            if (len(str(c).strip()) <= 5) or (len(str(c).strip()) > 9):
                corfor = "USA"
            else:
                corfor = "CAN"
        else:
            corfor = "Bad Data"
    else:
        for col in Nafta:
            if Nafta.loc[Nafta[col] == a].empty != True:
                score = "good" 
                corfor = Nafta.iloc[Nafta.loc[Nafta[col] == a].index[-1],1]
                break
            else:
                score = "pending"
                continue
    if  "pending" == score:
        for col in Country:
            if Country.loc[Country[col]== a].empty != True:
                score = "good"
                corfor = Country.iloc[Country.loc[Country[col] == a].index[-1],2]
                break
            else:
                score = "bad"
                corfor = "Bad Data"
                continue
    return score, corfor

origin["Origin Ctry Score"] , origin["Origin Ctry Format"] = zip(*origin.apply(lambda x: CountryScore(x["Origin Ctry"], x["Origin State"], x["Origin Zip"]), axis = 1))

假設數據幀已經加載。 謝謝!!!

我能夠找到我的錯誤。 在“國家/地區”的最后一列中,我將整數與字符串進行比較。 與布爾值無關。 固定於:

Country.loc[Country[col].astype(str)== a].empty != True

最后,我將總結這種類型的轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM