在转置并添加几列之后,我已经创建了如下所示的数据框。
初始df-
plan_benefits value plan_benefits_db value_db valid_flag
0 durable_medical_equipment 20 durable_medical_equipment 40 False
1 pcp 45 pcp 40 False
2 specialist 80 specialist 40 False
3 diagnostic 7540 diagnostic 40 False
4 imaging 300 imaging 40 False
5 generic 30 generic 40500 False
6 formulary_brand 110 formulary_brand 40500 False
7 non_preferred_generic 55110 non_preferred_generic 40500 False
8 emergency_room 350 emergency_room 40 False
9 inpatient_facility 20 inpatient_facility 40 False
10 medical_deductible_single 2000 medical_deductible_single 6000 False
11 medical_deductible_family 4000 medical_deductible_family 12000 False
12 maximum_out_of_pocket_limit_single 7550 maximum_out_of_pocket_limit_single 6650 False
13 maximum_out_of_pocket_limit_family 15100 maximum_out_of_pocket_limit_family 13300 False
最终df-
plan_benefits 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
valid_flag False False False False False False False False False False False False False False ABCBCBC adjnajdn.pdf
我执行的操作-
df_repo = df_repo[['plan_benefits', 'valid_flag']].set_index('plan_benefits').transpose()
df_repo['plan_name'] = 'ABCBCBC'
df_repo['pdf_name'] = 'adjnajdn.pdf'
# df_repo = df_repo.drop('plan_benefits', 1)
print(df_repo.to_string())
我需要删除第一列“ plan_benefits”。使用drop()
时,我得到KeyError: "['plan_benefits'] not found in axis"
我尝试了多个选项,例如del df ['plan_benefits'],但没有任何效果。
评论后的最终答案-
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
答案 0 :(得分:0)
首先需要删除列名称并创建默认索引:
df = (df_repo[['plan_benefits', 'valid_flag']].set_index('plan_benefits')
.T.reset_index(drop=True))
df.columns.name = None
或者:
df = (df_repo[['plan_benefits', 'valid_flag']]
.set_index('plan_benefits')
.transpose()
.reset_index(drop=True)
.rename_axis(None, axis=1))
print (df)
durable_medical_equipment pcp specialist diagnostic imaging generic \
0 False False False False False False
formulary_brand non_preferred_generic emergency_room inpatient_facility \
0 False False False False
medical_deductible_single medical_deductible_family \
0 False False
maximum_out_of_pocket_limit_single maximum_out_of_pocket_limit_family
0 False False
最后将index=False
添加到DataFrame.to_excel
:
df.to_excel('file.xlsx', index=False)
顺便说一句,由于删除了索引,因此应简化解决方案:
df = df_repo[['plan_benefits', 'valid_flag']].set_index('plan_benefits').transpose()
df.to_excel('file.xlsx', index=False)