写入Excel时如何在groupby之后在数据框中删除空值

问题描述

我有以下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的{​​{1}}的一列COLS进行分组,按dfe分组,并用excel编写,使每个ID数据都在一张纸上。 我试过的:-

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() 的许多列为0之后,我想删除groupby之后且写入excel之前为空的列。我无法删除groupby之前的空列,因为整个列将不为空

解决方法

您可以通过def custom_mse(): def mse(y_true,y_pred): great = K.tf.greater(y_true,0.5) loss = K.square(tf.where(great,y_true,tf.zeros(tf.shape(y_true)))-tf.where(great,y_pred,tf.zeros(tf.shape(y_pred)))) lower = K.tf.less(y_true,0.5) loss_low = K.square(tf.where(lower,tf.zeros(tf.shape(y_true)))-tf.where(lower,tf.zeros(tf.shape(y_pred)))) return 100*loss+loss_low return mse how='all'参数删除DataFrame.dropna仅缺少值的所有列:

axis=1