使用pandas将字典数据复制到csv

时间:2018-10-17 06:01:37

标签: python pandas

当我打印temp_dict时,就是这样,

 {u'part_b_deductible': None, u'off_exchange': True, u'plan_description': None, u'sbc_download_url': None, u'price_note': None, u'starting_percentage_fpl': 0.0, u'is_uhc_plan': False, 'issuer_id': (484,), u'promotional_label': None, u'metal_level_name': u'Silver', u'network_url': None, u'group_or_individual_plan_type': u'Group', u'treatment_cost_calculator_url': None, u'hios_plan_identifier': u'99806CAAUSJ-TMP', u'original_medicare': None, u'part_d_prescription_coverage': None, u'data_sourced_from': u'uhc', u'price_period': u'Monthly', u'is_age_29_plan': False, u'type': u'MetalPlan', u'plan_year': 2018.0, u'plan_detail_footer': None, u'default_bhp': None, u'formulary_url': None, u'plan_detail_items': None, u'highlight_6': None, u'highlight_4': None, u'highlight_5': None, u'hsa_eligible': 0.0, u'highlight_3': u'PCP 20% coinsurance', u'highlight_1': u'Silver', u'name': u'WI 80 INDEMNITY 18 OPTION 1 SILVER RX $10/45/90/25%', u'network_description': None, u'plan_detail_header': None, 'service_area_id': (1,), u'ending_percentage_fpl': 0.0, u'highlight_2': u'Indemnity', u'on_exchange': False, u'network_type': u'Indemnity', u'recommended': None}

但是当我将其复制到csv中时,那里的数据是-

,data_sourced_from,default_bhp,ending_percentage_fpl,formulary_url,group_or_individual_plan_type,highlight_1,highlight_2,highlight_3,highlight_4,highlight_5,highlight_6,hios_plan_identifier,hsa_eligible,is_age_29_plan,is_uhc_plan,issuer_id,metal_level_name,name,network_description,network_type,network_url,off_exchange,on_exchange,original_medicare,part_b_deductible,part_d_prescription_coverage,plan_description,plan_detail_footer,plan_detail_header,plan_detail_items,plan_year,price_note,price_period,promotional_label,recommended,sbc_download_url,service_area_id,starting_percentage_fpl,treatment_cost_calculator_url,type
0,uhc,,0.0,,Group,Silver,Indemnity,PCP 20% coinsurance,,,,99806CAAUSJ-TMP6,0.0,False,False,484,Silver,WI 80 INDEMNITY 18 OPTION 1 SILVER RX $10/45/90/25%,,Indemnity,,True,False,,,,,,,,2018.0,,Monthly,,,,1,0.0,,MetalPlan

使用以下代码:

  (pd.DataFrame.from_dict(data=temp_dict, orient='columns')
                             .to_csv('dump.csv', header=True))

为什么以逗号开头?

编辑-:

不确定为什么对这个问题投反对票。请问可以否投票。

2 个答案:

答案 0 :(得分:2)

使用参数index=False

pd.DataFrame.from_dict(data=temp_dict, orient='columns')
            .to_csv('dump.csv', header=True, index=False)

如果只需要标题:

pd.DataFrame(columns=df.columns.tolist()).to_csv('dump.csv', index=False)

答案 1 :(得分:1)

尝试一下:

df = pd.DataFrame(temp_dict)
df.to_csv('dump.csv', sep=',', index=None)