0

我的错误是:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-88-b8c70965fe8e> in <module>
     10         new_df["CustomerLocation"] = new_df.CustomerLocation.replace(x, (float(x[0]), float(x[1])))
     11         print("floated x:", new_df.CustomerLocation)
---> 12         new_df["MerchantLocation"] = new_df.MerchantLocation.replace(y, (float(y[0]), float(y[1])))
     13         print(haversine((float(x[0]), float(x[1])), (float(y[0]), float(y[1])), unit='mi'), "miles")
     14     else:

ValueError: could not convert string to float: 'n/a'

我的代码是:

new_df=pd.DataFrame({'MerchantLocation':(tuple(num) for num in data.merchant_long_lat), 'CustomerLocation': (tuple(num) for num in data.long_lat)})

for index, row in new_df.iterrows():
    x=row.CustomerLocation
    y=row.MerchantLocation
    #new_df["MerchantLocation"] = new_df.MerchantLocation.replace(y, (y[0].replace(r'^\s*$', np.NaN, regex=True), y[1].replace(r'^\s*$', np.NaN, regex=True)))

    if x[0]!="" or x[1]!="" or y[0]!="" or y[1]!="":
        print("x:",x)
        new_df["CustomerLocation"] = new_df.CustomerLocation.replace(x, (float(x[0]), float(x[1])))
        new_df["MerchantLocation"] = new_df.MerchantLocation.replace(y, (float(y[0]), float(y[1])))
        print(haversine((float(x[0]), float(x[1])), (float(y[0]), float(y[1])), unit='mi'), "miles")
    else:
        print("There is an empty string")

当我检查时,原始 Excel 数据中有一个空单元格。这是来自 ANZ 的虚拟实习。我无法捕捉到空字符串。请帮忙!

4

1 回答 1

0

尝试使用 try-catch 语句包围有问题的代码区域。就像是:

if x[0]!="" or x[1]!="" or y[0]!="" or y[1]!="":
    try:
        print("x:",x)
        new_df["CustomerLocation"] = new_df.CustomerLocation.replace(x, (float(x[0]), float(x[1])))
        new_df["MerchantLocation"] = new_df.MerchantLocation.replace(y, (float(y[0]), float(y[1])))
        print(haversine((float(x[0]), float(x[1])), (float(y[0]), float(y[1])), unit='mi'), "miles")
    except:
        print("one of these should be N/A")
        print(x[0], x[1], y[0], y[1])
else:
    print("There is an empty string")
于 2021-11-11T18:24:39.213 回答