【发布时间】:2019-12-28 17:18:39
【问题描述】:
我有两个数据框(df1 和 df2,如下所示),它们的列在顺序和计数上都不同。我需要将这两个数据框附加到一个 Excel 文件中,其中列顺序必须按照下面Col_list 中的指定。
df1 是:
durable_medical_equipment pcp specialist diagnostic imaging generic formulary_brand non_preferred_generic emergency_room inpatient_facility medical_deductible_single medical_deductible_family maximum_out_of_pocket_limit_single maximum_out_of_pocket_limit_family plan_name pdf_name
0 False False False False False False False False False False False False False False ABCBCBC adjnajdn.pdf
... df2 是:
pcp specialist generic formulary_brand emergency_room urgent_care inpatient_facility durable_medical_equipment medical_deductible_single medical_deductible_family maximum_out_of_pocket_limit_single maximum_out_of_pocket_limit_family plan_name pdf_name
0 True True False False True True True True True True True True ABCBCBC adjnajdn.pdf
我正在创建一个与 excel 中的列顺序相同的列列表。
Col_list = ['durable_medical_equipment', 'pcp', 'specialist', 'diagnostic',
'imaging', 'generic', 'formulary_brand', 'non_preferred_generic',
'emergency_room', 'inpatient_facility', 'medical_deductible_single',
'medical_deductible_family', 'maximum_out_of_pocket_limit_single', 'maximum_out_of_pocket_limit_family',
'urgent_care', 'plan_name', 'pdf_name']
我正在尝试使用 concat() 根据 Col_list 重新排序我的数据框。对于数据框中不存在的列值,该值可以是 NaN。
result = pd.concat([df, pd.DataFrame(columns=list(Col_list))])
这不能正常工作。我怎样才能实现这种重新排序?
我尝试了以下方法:
result = pd.concat([df_repo, pd.DataFrame(columns=list(Col_list))], sort=False, ignore_index=True)
print(result.to_string())
我得到的输出是:
durable_medical_equipment pcp specialist diagnostic imaging generic formulary_brand non_preferred_generic emergency_room inpatient_facility medical_deductible_single medical_deductible_family maximum_out_of_pocket_limit_single maximum_out_of_pocket_limit_family plan_name pdf_name urgent_care
0 False False False False False False False False False False False False False False ABCBCBC adjnajdn.pdf NaN
pcp specialist generic formulary_brand emergency_room urgent_care inpatient_facility durable_medical_equipment medical_deductible_single medical_deductible_family maximum_out_of_pocket_limit_single maximum_out_of_pocket_limit_family plan_name pdf_name diagnostic imaging non_preferred_generic
0 True True False False True True True True True True True True ABCBCBC adjnajdn.pdf NaN NaN NaN
【问题讨论】:
-
使用
concat而不是merge似乎是一个错误,因为您的数据框共享许多公共列 (pcp, specialist, generic)。您真的希望这些列在输出中显示两次吗? -
使用 concat,它不会给我重复
-
当您想组合 2+ 个具有共享列的数据框时,请使用
merge而不是concat:Difference(s) between merge() and concat() in pandas