【问题标题】:Dict showing as None when passed into function传递给函数时,字典显示为无
【发布时间】:2017-10-24 18:05:09
【问题描述】:

我有一个执行 API 调用并返回记录的函数,该记录最终将转换为数据框。

处理请求的两个函数如下:

def get_json(url, params={}):
    headers = {"Authorization": "Bearer {}".format(get_token())}
    r = requests.get(url, params=params, headers=headers)
    return r.json()


def retrieve_record(record=None, profile_ID=None, page_ID=None):
    profile_ID = str(profile_ID)
    pages_ID = str(page_ID)
    print_function_call("retrieve_record()", [profile_ID, pages_ID])
    return get_json(root_path + '/exzact/api/v60/profiles/{}/pages/{}/records/{}'.format(profile_ID, pages_ID, record))

它返回一个对象,然后我将其打印到控制台。该对象非常长,但看起来像这样:

{u'created_date': u'2017-10-24T17:41:15+00:00', ...}

对象内部显然有数据。但是当我尝试将其转换为这样的数据框时:

df = pd.DataFrame()
obj = retrieve_record(profile_ID=profile_ID, page_ID=page_ID, record=ID)
data = pd.DataFrame.from_dict(obj, orient='index')

我收到此错误作为响应:

Error: object of type 'NoneType' has no len()

现在我可以假设错误发生在pd.DataFrame.from_dict() 函数调用中。但我说不出为什么。我传递的字典中显然有数据,但它被评估为NoneType

我正在寻找有关我的字典对象可能出现问题的建议。是不是字典中的某些字段属于NoneType,而不是整个对象本身?

追溯

Traceback (most recent call last):
  File "", line 456, in <module>
    newDF = create_DF(profile_ID, page_ID, today_ids)
  File "", line 211, in create_DF
    data = pd.DataFrame.from_dict(obj, orient='index')
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 861, in from_dict
    return cls(data, index=index, columns=columns, dtype=dtype)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 314, in __init__
    arrays, columns = _to_arrays(data, columns, dtype=dtype)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 5715, in _to_arrays
    dtype=dtype)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 5792, in _list_to_arrays
    content = list(lib.to_object_array(data).T)
  File "pandas\_libs\src\inference.pyx", line 1614, in pandas._libs.lib.to_object_array (pandas\_libs\lib.c:66831)
TypeError: object of type 'NoneType' has no len()

完整词典

{u'company_sub_post_installation_clean_up': [], u'dcms_': u'890835', u'email_inspection': None, u'company_sub_welding': [], u'company_sub_joining_plastic': [], u'job_type': u'service', u'job_material_type': u'plastic', u'if_other_type_crew_leader_name': None, u'company_sub_safety': [{u'equipment_safety_functional': None, u'fire_extinguisher_being_used': u'meets', u'appropriate_ppe_was_used': u'meets', u'server_modified_date': u'2017-10-24T17:41:15+00:00', u'id': 69, u'parent_element_id': 277320543, u'vehicletrailerequipment_cones_present': u'meets', u'modified_date': u'2017-10-24T17:39:22+00:00', u'vehicletrailer_wheel_chocks_present': u'meets', u'modified_by': u'company', u'fire_extinguisher_date_acceptable': u'meets', u'chemicals_properly_labeled_hazcom': None, u'created_by': u'company', u'safety_comments__photos': [], u'modified_device_id': u'990006001231835', u'complete_trench_entry_form': None, u'created_location': u'35.625220:-80.467894:0.000000:24.400999:24.400999:0.000000:0.000000:1508866785280.000000', u'appropriate_traffic_control_was_used': u'meets', u'select_items_not_met': None, u'javascript_state': u'{}', u'fire_extinguisher_fully_charged': u'meets', u'gas_co_oxygen_detector_used': None, u'parent_record_id': 87, u'shoring_equipment_trench_box_operation': None, u'shoring_used': None, u'modified_location': u'35.625220:-80.467894:0.000000:24.400999:24.400999:0.000000:0.000000:1508866785280.000000', u'parent_page_id': 3440925, u'ladder_operation_acceptable': None, u'ladder_used': None, u'created_device_id': u'990006001231835', u'equipment_safety_being_used': None, u'select_trafic_items_not_met': None, u'equipmenttools_proper_distance_from_trench': None, u'created_date': u'2017-10-24T17:39:22+00:00', u'prejob_brief_was_performed_and_documented': u'meets'}], u'server_modified_date': u'2017-10-24T17:41:14+00:00', u'id': 87, u'parent_element_id': 0, u'date1': u'2017-10-24', u'modified_date': u'2017-10-24T17:41:06+00:00', u'company_sub_trench': [{u'modified_date': u'2017-10-24T17:39:32+00:00', u'javascript_state': u'{}', u'parent_page_id': 3440925, u'no_weak_link_issues': None, u'oq_present_texca001_inspection_of_excavation_activities': u'meets', u'server_modified_date': u'2017-10-24T17:41:16+00:00', u'created_device_id': u'990006001231835', u'parent_record_id': 87, u'depth_consistent_along_trenchline': None, u'created_by': u'company', u'trench_photos__comments': [], u'trench_depth_adequate': None, u'modified_device_id': u'990006001231835', u'trench_width_adequate': None, u'created_date': u'2017-10-24T17:39:32+00:00', u'modified_by': u'company', u'created_location': u'35.625220:-80.467894:0.000000:24.812000:24.812000:0.000000:0.000000:1508866785280.000000', u'modified_location': u'35.625220:-80.467894:0.000000:24.812000:24.812000:0.000000:0.000000:1508866785280.000000', u'id': 48, u'parent_element_id': 277320810, u'proper_dewatering': None}], u'modified_by': u'company', u'job_materials_photos__comments': [], u'created_by': u'company', u'catalogue_number': None, u'company_sub_pressure_test': [], u'company_sub_working_around_utilities': [], u'modified_device_id': u'990006001231835', u'crew_leader': u'kenneth_black__n18031', u'company_sub__purging__abandon': [], u'title__address': u'464 Sonoma dr', u'damaged_material_repaired_or_removed': None, u'company_sub_equipment_and_tools': [], u'type_of_nonconformance': None, u'company_sub_tie_ins': [], u'pipe_within_allowable_date_range': u'meets', u'pipe_materials_properly_marked': u'meets', u'javascript_state': u'null', u'responsible_for_nonconformance': None, u'company_sub_job_documentation': [], u'company_sub_design_adherance': [], u'company_sub_backfilling': [], u'parent_record_id': 0, u'job_sub_type': u'residential', u'my_element4': u'', u'company_sub_pigging': [], u'company_sub_coating': [], u'company_sub_cathodic_protection': [], u'company_sub_bore': [{u'proper_depth': u'meets', u'bore_photos__comments': [], u'visual_inspection_of_pipe_during_pullback': None, u'environmental_standards__protections_observered': None, u'server_modified_date': u'2017-10-24T17:41:17+00:00', u'id': 18, u'parent_element_id': 277320816, u'modified_date': u'2017-10-24T17:39:48+00:00', u'modified_by': u'company', u'no_head_size_problems_size_of_reamer_appropriate': None, u'created_by': u'company', u'modified_device_id': u'990006001231835', u'created_location': u'35.624811:-80.468068:0.000000:27.521999:27.521999:0.000000:0.000000:1508866785280.000000', u'type_of_bore': None, u'no_weak_link_issues': None, u'javascript_state': u'{}', u'bore_profile_present': None, u'parent_record_id': 87, u'modified_location': u'35.624811:-80.468068:0.000000:27.521999:27.521999:0.000000:0.000000:1508866785280.000000', u'parent_page_id': 3440925, u'created_device_id': u'990006001231835', u'permitting_adequate': None, u'tracer_wire_present': None, u'created_date': u'2017-10-24T17:39:48+00:00'}], u'modified_location': u'35.625220:-80.467894:0.000000:25.257000:25.257000:0.000000:0.000000:1508866785280.000000', u'created_location': u'35.624811:-80.468068:0.000000:22.379999:22.379999:0.000000:0.000000:1508866654208.000000', u'company_inspected': u'mears_construction', u'project_ir_': u'08003', u'parent_page_id': 0, u'created_device_id': u'990006001231835', u'asset_information_multiple': [{u'date_a1_value': u'', u'picture_of_asset': None, u'data_value': u'', u'd_value': u'0', u'data_result': u'', u'lot_code_code': None, u'size_code': None, u'material_type': u'plastic_pipe', u'a4_lotcode': u'', u'lot_code': u'0', u'a1v': u'', u'a2_lotcode_code': None, u'c2_final_value': u'', u'c2': None, u'date_a3_code': u'', u'c1_final': u'', u'production_date_leap_year': u', 200', u'server_modified_date': u'2017-10-24T17:41:15+00:00', u'id': 51, u'parent_element_id': 277320738, u'a3v': u'', u'modified_date': u'2017-10-24T17:38:41+00:00', u'modified_by': u'company', u'a2_lotcode': u'', u'production_date': u', 200', u'dayly_final': u'', u'picture_of_nonconformance': None, u'a1_lotcode': u'', u'data_result_split': u' ', u'c1_final_value': u'', u'created_by': u'company', u'a3_lotcode': u'', u'date_code': None, u'modified_device_id': u'990006001231835', u'lotcodesplit': u'', u'date_a1_code': None, u'created_location': u'35.624811:-80.468068:0.000000:22.379999:22.379999:0.000000:0.000000:1508866654208.000000', u'leap_year': u'0', u'type_of_nonconformance': None, u'a3_lotcode_code': None, u'a4_lotcode_code': u'', u'component_type_code': None, u'javascript_state': u'{}', u'size_split': u'', u'responsible_for_nonconformance': None, u'a2v': u'', u'c2_final': u'', u'material': u'', u'parent_record_id': 87, u'year1': u'200', u'a1': None, u'barcode_on_fitting__pipe': None, u'a2': None, u'date_a3_value': u'', u'a1_lotcode_code': None, u'manufacturer_code': u' ', u'modified_location': u'35.624811:-80.468068:0.000000:22.379999:22.379999:0.000000:0.000000:1508866654208.000000', u'catalogue_number': None, u'date_d_value_split': u'||0', u'date_a2_value': u'', u'day_final': u'', u'parent_page_id': 3440925, u'd': u'0', u'component_type': u'', u'day_ly_raw': u'', u'created_device_id': u'990006001231835', u'a3': u'', u'date_code_split': u'', u'material_code': None, u'day_raw': u'', u'manufacturer': u'', u'created_date': u'2017-10-24T17:38:40+00:00', u'date_a2_code': None, u'nonconformance_': u'No', u'display': None}], u'matieral_condition': u'meets', u'company_sub_material_handling': [], u'company_sub_manuals': [], u'created_date': u'2017-10-24T17:38:25+00:00', u'inspector_id': u'company', u'inspection_overall_comments_and_photos': [], u'company_sub_environmental': []}

【问题讨论】:

  • 请显示完整的回溯。
  • @DanielRoseman 已更新。
  • @PRMoureu 你能扩展一下吗?此代码是从熟悉 pandas 库的前员工那里重用的。由于我自己不熟悉,这使问题更难解决。
  • 你能展示一个更大的字典样本吗?
  • @PRMoureu 是的,给我一秒钟。

标签: python json pandas dictionary


【解决方案1】:

但很明显,字典键,例如:u'company_sub_post_installation_clean_up' 和相应的值似乎一开始就无效,所以我想这些应该被整理出来,这样就不会产生任何 None- 条目。但是,如果您的解决方法可以解决问题,那就太好了!

【讨论】:

  • 我认为部分混淆来自于一些键的值是深层对象(记录的子形式)。我的想法是,我必须先将对象压平,然后才能将其打印出来。我花了很长时间才意识到它们实际上只是空的。尽管如此,我还是感谢您的帮助。
【解决方案2】:

也许返回 r.json().decode('utf-8') 会对此有所帮助?

【讨论】:

  • AttributeError: 'list' object has no attribute 'decode'
  • r.decode('utf-8').json()?这只是猜测,但似乎 get() 返回编码数据...
  • AttributeError: 'Response' object has no attribute 'decode'。不知道这里发生了什么。我会继续玩弄响应
  • 打印r.encoding 返回None。但这没有任何意义,因为在字典中显然可以看到 u` 字符
  • 您可以迭代 'r' 中的所有条目并在返回之前将 .encode('utf-8') 应用于所有条目
【解决方案3】:

在这里回答我自己的问题:

问题不在于字典本身是None,而是它包含None 类型的值。之所以没有注意到这一点,是因为我们之前使用脚本需要填写记录中的所有字段。

而这一次,很多记录字段都是可选的。在将None 键/值对转换为DataFrame 之前,必须从字典中删除它们。删除它们后,错误将不再存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2010-09-24
    • 2011-03-14
    • 2017-10-01
    • 2023-03-26
    相关资源
    最近更新 更多