Pandas 如何在写入excel时在groupby之后删除dataframe中的空值
我有以下Pandas 如何在写入excel时在groupby之后删除dataframe中的空值,pandas,dataframe,pivot,export-to-excel,Pandas,Dataframe,Pivot,Export To Excel,我有以下dfe:- ID CATEG LEVEL COLS VALUE COMMENTS 1 A 2 Apple 428 comment1 1 A 3 Apple 175 comment1 1 C 1 Apple 226 comment1 1 C 2 Apple 884 comment1 1 C
dfe
:-
ID CATEG LEVEL COLS VALUE COMMENTS
1 A 2 Apple 428 comment1
1 A 3 Apple 175 comment1
1 C 1 Apple 226 comment1
1 C 2 Apple 884 comment1
1 C 3 Apple 289 comment1
1 B 1 Apple 712 comment1
1 B 2 Apple 849 comment1
2 B 3 Apple 376 comment1
2 C None Orange 591 comment1
2 B None Orange 135 comment1
2 D None Orange 423 comment1
2 A None Orange 866 comment1
2 None Orange 496 comment2
我想通过dfe
的一列COLS
,groupbyID
透视,并在excel中编写,以便每个ID
数据都在一张表上。
我尝试的是:-
df=pd.pivot_table(dfe,index=['ID','CATEG','LEVEL'],columns=['COLS'],values=['VALUE'])
with pd.ExcelWriter('file.xlsx',options={'nan_inf_to_errors': True}) as writer :
df.groupby('ID').apply(lambda x: x.to_excel(writer,sheet_name=str(x.name),na_rep=0,index=True))
writer.save()
我面临的问题是,在groupby
之后,许多列都是0,我想删除groupby
之后和写入excel之前为空的列。我无法在groupby
之前删除空列,因为整个列不会为空,然后您可以通过how='all'
和axis=1
参数删除所有只缺少值的列:
with pd.ExcelWriter('file.xlsx',options={'nan_inf_to_errors': True}) as writer :
df.groupby('ID').apply(lambda x: x.dropna(how='all', axis=1).to_excel(writer,sheet_name=str(x.name),na_rep=0,index=True))
writer.save()
你好感谢您的回复,这很有效,但我无法在一行中获得所有标题,我如何做到这一点,例如:0值
显示在第一行,然后在第二行显示轴列标题,在下一行显示ID
,CATEG
,LEVEL
,我希望所有标题都显示在一行中,我如何做到这一点header=false
删除所有3行的更改df=pd.pivot_表(dfe,index=['ID','CATEG','LEVEL',columns=['COLS',values=['VALUE'])
到df=pd.pivot_表(dfe,index=['ID','CATEG','LEVEL',columns='COLS',values='VALUE'])
工作正常。我面临一个问题,所有数字都以scinetifc格式出现,pd.options.display.float_format='{.2f}'。format
this@Scope-一些想法-.所有这些我试图避免的转换成浮动,因为我的数据中没有任何浮点值。。