如何实现数据框对象的重采样均值,以便在均值计算中排除零值

how to implement Resampling mean of dataframe object such that zero values are excluded in calculation of mean

我有一个带有时间戳值的数据框。我已经能够弄清楚如何使用数据框的重采样方法并将函数 last() 或 mean() 应用于结果。我这样做如下:

print(type(df.timestamp))
print(type(df.timestamp[0]))
df=df.set_index('timestamp')
df_1=df.resample('60S').last()
df_2=df.resample('60S').mean()

<class 'pandas.core.series.Series'>
<class 'pandas._libs.tslibs.timestamps.Timestamp'>

在这里,df_1 给我的结果是每个重采样周期中的最后一个值,df_2 给我的结果是每个重采样周期中所有值的平均值。

现在的问题是我的数据包含很多零值,所以我希望 df_1 的结果包含最后一个非零值,df_2 的结果只包含那些值的平均值是非零的。我无法在文档 (resampling link).

中找到这样做的方法

请提出实现此目的的适当方法。

zero可以换成np.nan然后应用函数

df=pd.DataFrame({
    'timestamp':pd.date_range('2020.01.01', periods=6, freq='30S'),
    'val':[1,2,3,0,0,4]
})
df=df.set_index('timestamp')
df.val = df.val.replace(0, np.nan)
df = df.resample('60s').agg(['mean','last'])
df

输出

                      val
                      mean     last
timestamp       
2020-01-01 00:00:00   1.5       2.0
2020-01-01 00:01:00   3.0       3.0 
2020-01-01 00:02:00   4.0       4.0