与Pandas中的布尔值进行无效类型比较

时间:2019-02-05 04:17:11

标签: python python-3.x pandas numpy type-conversion

尝试基于其他行级数据或具有类似数据的其他数据框来清理pandas数据框(来源)中的“国家(地区)”列。请参阅链接,例如数据帧。

它最终将在数据框中提供两个新列,从而提供正确格式的国家/地区和数据质量“得分”。

Origin Dataframe Nafta, Countries, and States DataFrames

该函数适用于查找表或空白中的值,但是当我传入“不良”数据时,它给出了无效的类型比较。分别进行测试将返回一个布尔值,并且可以正常工作:

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))

假设已加载数据帧。谢谢!!!

1 个答案:

答案 0 :(得分:0)

我能够找到我的错误。在“国家/地区”的最后一列中,我将整数与字符串进行比较。与布尔值无关。固定为:

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

在这种类型的转换中,我将得到最多的包裹。

相关问题