我有以下内容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
我想pivot
通过一列COLS
的dfe
,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
因为整个列将不为空
您可以DataFrame.dropna
通过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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句