指定lambda函数以继续即使出现错误

时间:2018-12-31 18:45:47

标签: python pandas lambda

我正在尝试运行以下代码行:

df['Zillow ID'] = df.apply(lambda row: get_zillow_id(key, row['Address'], row['Zipcode']), axis = 1)

但是对于某些地址和邮政编码,函数get_zillow_id()失败。但我希望lambda函数只忽略该特定地址和邮政编码的错误并继续。我该怎么办?

这是完整的代码:

from pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults, GetUpdatedPropertyDetails
import pandas as pd
import numpy as np

key = "X1-ZWz1gtmiat11xn_7ew1d"



# Create function to get zillow_id
def get_zillow_id(key, address, zipcode):
    zillow_data = ZillowWrapper(key)
    deep_search_response = zillow_data.get_deep_search_results(address, zipcode)
    result = GetDeepSearchResults(deep_search_response)
    return result.zillow_id



# Create function to get propery data
def get_property_data(key, address, zipcode):
    zillow_data = ZillowWrapper(key)
    updated_property_details_response = zillow_data.get_updated_property_details(get_zillow_id(key, address, zipcode))
    result = GetUpdatedPropertyDetails(updated_property_details_response)
    return result.year_built





# Import data into dataframe
df = pd.read_csv('test.csv')

# Get zillow ids

df['Zillow ID'] = df.apply(lambda row: get_zillow_id(key, row['Address'], row['Zipcode']), axis = 1)

这是数据帧的图片:

enter image description here

这是我遇到的错误:

ZillowError                               Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_code(self, code_obj, result)
   2861                 #rprint('Running code', repr(code_obj)) # dbg
-> 2862                 exec(code_obj, self.user_global_ns, self.user_ns)
   2863             finally:

<ipython-input-40-55f38b77eeea> in <module>()
      1 # Get zillow ids
----> 2 df['Zillow ID'] = df.apply(lambda row: get_zillow_id(key, row['Address'], row['Zipcode']), axis = 1)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
   4261                         reduce=reduce,
-> 4262                         ignore_failures=ignore_failures)
   4263             else:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
   4357                 for i, v in enumerate(series_gen):
-> 4358                     results[i] = func(v)
   4359                     keys.append(v.name)

<ipython-input-40-55f38b77eeea> in <lambda>(row)
      1 # Get zillow ids
----> 2 df['Zillow ID'] = df.apply(lambda row: get_zillow_id(key, row['Address'], row['Zipcode']), axis = 1)

<ipython-input-37-ce158395fdb8> in get_zillow_id(key, address, zipcode)
      3     zillow_data = ZillowWrapper(key)
----> 4     deep_search_response = zillow_data.get_deep_search_results(address, zipcode)
      5     result = GetDeepSearchResults(deep_search_response)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pyzillow\pyzillow.py in get_deep_search_results(self, address, zipcode)
     30         }
---> 31         return self.get_data(url, params)
     32 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pyzillow\pyzillow.py in get_data(self, url, params)
     81         if response.findall('message/code')[0].text is not '0':
---> 82             raise ZillowError(int(response.findall('message/code')[0].text))
     83         else:

<class 'str'>: (<class 'TypeError'>, TypeError('__str__ returned non-string (type dict)',))

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_code(self, code_obj, result)
   2877             if result is not None:
   2878                 result.error_in_exec = sys.exc_info()[1]
-> 2879             self.showtraceback(running_compiled_code=True)
   2880         else:
   2881             outflag = False

~\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py in showtraceback(self, exc_tuple, filename, tb_offset, exception_only, running_compiled_code)
   1809                                             value, tb, tb_offset=tb_offset)
   1810 
-> 1811                     self._showtraceback(etype, value, stb)
   1812                     if self.call_pdb:
   1813                         # drop into debugger

~\AppData\Local\Continuum\anaconda3\lib\site-packages\ipykernel\zmqshell.py in _showtraceback(self, etype, evalue, stb)
    541             u'traceback' : stb,
    542             u'ename' : unicode_type(etype.__name__),
--> 543             u'evalue' : py3compat.safe_unicode(evalue),
    544         }
    545 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\ipython_genutils\py3compat.py in safe_unicode(e)
     63     """
     64     try:
---> 65         return unicode_type(e)
     66     except UnicodeError:
     67         pass

TypeError: __str__ returned non-string (type dict)

1 个答案:

答案 0 :(得分:1)

您应该尝试准确地理解为什么为什么您的函数将失败。然后,使用try / except子句忽略要避免的特定问题。例如,忽略TypeError

def get_zillow_id(key, address, zipcode):
    try:
        zillow_data = ZillowWrapper(key)
        deep_search_response = zillow_data.get_deep_search_results(address, zipcode)
        result = GetDeepSearchResults(deep_search_response)
        return result.zillow_id
    except TypeError, ZillowError:
        return None

df['Zillow ID'] = df.apply(lambda row: get_zillow_id(key, row['Address'], row['Zipcode']),
                           axis=1)

如果ZillowError是实际错误,则可能需要从该库中导入它。