计算数据帧中数据段的平均值
问题描述
在下面的图片中,我有一个巨大的数据帧。对于每一次冲程,机器都会呈现穿透值,然后给零。我想计算一下每划一划的平均数。例如,[0.762,0.766]的平均值,以及[0.66,1.37,2.11,2.29]的平均值,依此类推,直到数据帧结束。请注意,笔划没有固定的长度。enter image description here
解决方案
# Generate example data based on your image
df = pd.DataFrame({'penetration':
[0, 1, 0, 2, 3, 0, 0,
5, 6, 7, 0, 0, 0, 0]})
# Flag rows with nonzero penetration depth
df['segment'] = df['penetration'].ne(0)
# Flag rows which represent a change from non-segment
# to segment, or from segment to non-segment
df['group'] = df['segment'].ne(df['segment'].shift())
# Label each segment with a unique integer
df['group'].cumsum()
# Zero out the group number of rows which belong to non-segments
df['group'] = df['group'].where(df['segment'], 0)
# Get mean of penetration depths for each group
df['mean'] = df.groupby('group')['penetration'].transform('mean')
# Print result
df
penetration segment group mean
0 0 False 0 0.0
1 1 True 2 1.0
2 0 False 0 0.0
3 2 True 4 2.5
4 3 True 4 2.5
5 0 False 0 0.0
6 0 False 0 0.0
7 5 True 6 6.0
8 6 True 6 6.0
9 7 True 6 6.0
10 0 False 0 0.0
11 0 False 0 0.0
12 0 False 0 0.0
13 0 False 0 0.0
相关文章