2016-03-08 71 views
1

我想將嵌套的json數組轉換爲熊貓數據框。將嵌套的json轉換爲熊貓數據框

數據如下列表格式是這樣的:

[{u'analysis': {u'active': u'Y', 
    u'dpv_cmra': u'N', 
    u'dpv_footnotes': u'AAN1', 
    u'dpv_match_code': u'D', 
    u'dpv_vacant': u'N', 
    u'footnotes': u'H#'}, 
    u'candidate_index': 0, 
    u'components': 
    {u'city_name': u'City', 
    u'delivery_point': u'Variable', 
    u'delivery_point_check_digit': u'8', 
    u'plus4_code': u'Variable', 
    u'primary_number': u'Variable', 
    u'state_abbreviation': u'Variable', 
    u'street_name': u'Variable', 
    u'street_predirection': u'Variable', 
    u'street_suffix': u'Variable', 
    u'zipcode': u'Variable'}, 
    u'delivery_line_1': u'Variable', 
    u'delivery_point_barcode': u'Variable', 
    u'input_id': u'Variable', 
    u'input_index': Variable, 
    u'last_line': u'Variable', 
    u'metadata': 
    {u'building_default_indicator': u'Variable', 
    u'carrier_route': u'Variable', 
    u'congressional_district': u'Variable', 
    u'county_fips': u'Variable', 
    u'county_name': u'Variable', 
    u'dst': True, 
    u'zip_type': u'Variable'}}], 

任何建議如何我可以將它轉換爲數據幀和取空值的照顧?我試過使用try /除了處理缺失的值,但我的數據框架是由元組組成的。

謝謝

回答

3

裏面有一個pd.io.json功能json_normalize

d = {u'analysis': {u'active': u'Y', u'dpv_cmra': u'N', u'dpv_footnotes': u'AAN1', u'dpv_match_code': u'D', u'dpv_vacant': u'N', u'footnotes': u'H#'}, u'candidate_index': 0, u'components': {u'city_name': u'City', u'delivery_point': u'Variable', u'delivery_point_check_digit': u'8', u'plus4_code': u'Variable', u'primary_number': u'Variable', u'state_abbreviation': u'Variable', u'street_name': u'Variable', u'street_predirection': u'Variable', u'street_suffix': u'Variable', u'zipcode': u'Variable'}, u'delivery_line_1': u'Variable', u'delivery_point_barcode': u'Variable', u'input_id': u'Variable', u'input_index': u'Variable', u'last_line': u'Variable', u'metadata': {u'building_default_indicator': u'Variable', u'carrier_route': u'Variable', u'congressional_district': u'Variable', u'county_fips': u'Variable', u'county_name': u'Variable', u'dst': True, u'zip_type': u'Variable'}} 

>>> pd.io.json.json_normalize(d) 
    analysis.active analysis.dpv_cmra analysis.dpv_footnotes analysis.dpv_match_code analysis.dpv_vacant analysis.footnotes candidate_index components.city_name components.delivery_point components.delivery_point_check_digit  ...   \ 
0    Y     N     AAN1      D     N     H#    0     City     Variable          8  ...   

    input_id input_index last_line metadata.building_default_indicator metadata.carrier_route metadata.congressional_district metadata.county_fips metadata.county_name metadata.dst metadata.zip_type 
0 Variable Variable Variable       Variable    Variable      Variable    Variable    Variable   True   Variable 

[1 rows x 29 columns] 
+1

非常酷......再一次熊貓io比任何其他東西都遙遙領先 – maxymoo

+0

這似乎工作,但我得到列表索引超出範圍? – bjurstrs

+0

沒關係,理清了它。感謝您的幫助! – bjurstrs