只有当值不为空时才进行计算

Conduct the calculation only when the value is not null

我有一个数据框dft:

Date              Total Value
02/01/2022          2
03/01/2022          6 
03/08/2022          4
03/11/2022          
03/15/2022          4
05/01/2022          4

我想计算三月份的总值,我用了下面的代码:

Mar22 = dft.loc[dft['Date'].between('03/01/2022', '03/31/2022', inclusive='both'),'Total Value'].sum()

03/11/2022 有空值,导致错误。我应该在我的代码中添加什么,以便我只对不为空的值求和?

会是isnull() == False吗?

这个问题是你有一个空字符串(它应该是一个 NaN)。

您可以确保只有数字 pandas.to_numeric:

out = (pd.to_numeric(df['Total Value'], errors='coerce')[dft['Date']
         .between('03/01/2022', '03/31/2022', inclusive='both')].sum()
      )

或者如果您只有空字符串作为非数值:

out = (dft.loc[dft['Date'].between('03/01/2022', '03/31/2022', inclusive='both'), 'Total Value']
          .replace('', float('nan')).sum()
       )

输出:14.0

试试 pandas built-in notnull() 函数。

Mar22 = dft.loc[dft['Total Value'].notnull()].loc[dft['Date'].between('03/01/2022', '03/31/2022', inclusive='both'),'Total Value'].sum()