Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

python - Count moving average in circle 360 degrees

This is my data

degree, value

0.0,0.42105263157894735
1.0,0.47368421052631576
2.0,0.47368421052631576
3.0,0.47368421052631576
4.0,0.5
5.0,0.5
6.0,0.5
7.0,0.47368421052631576
8.0,0.47368421052631576
9.0,0.47368421052631576
10.0,0.39473684210526316
..............
350.0,0.5263157894736842
351.0,0.5526315789473685
352.0,0.47368421052631576
353.0,0.47368421052631576
354.0,0.47368421052631576
355.0,0.4473684210526316
356.0,0.4473684210526316
357.0,0.4473684210526316
358.0,0.42105263157894735
359.0,0.42105263157894735

So, it is circle from 0 to 359 degrees.
I want to build moving average using these values. I do it with:

df['smoothing'] = df['value'].rolling(window=10).mean()   

    degree      value  smoothed
0      0.0   0.526316       NaN
1      1.0   0.000000       NaN
2      2.0   0.000000       NaN
3      3.0   0.000000       NaN
4      4.0   0.000000       NaN
..     ...        ...       ...
355  355.0   0.000000  0.000000
356  356.0   0.447368  0.044737
357  357.0   0.500000  0.094737
358  358.0   0.526316  0.147368
359  359.0   0.500000  0.197368

But there is a problem: I loose values from 0 to 9. They are important for me.
So, my script must use degrees 351,352,353,354,355 and so on to count average for degrees 0,1,2,3....

I expect output:

    degree      value                     smoothed
0      0.0   0.526316  mean value of 351-0 degrees
1      1.0   0.000000  mean value of 352-1 degrees
2      2.0   0.000000  mean value of 353-2 degrees
3      3.0   0.000000  mean value of 354-3 degrees
4      4.0   0.000000  mean value of 355-4 degrees
................
and so on    

How to do it? Thank you.

question from:https://stackoverflow.com/questions/65856307/count-moving-average-in-circle-360-degrees

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can prepend the last 9 values to the dataframe before taking the rolling mean so that 0 get's the mean value of 351-0, 1 gets the mean value of 352-1 and so on:

df1 = df[-9:].append(df)
df['smoothed'] = df1['value'].rolling(window=10).mean().dropna()

    degree     value  smoothed
0      0.0  0.421053  0.457895
1      1.0  0.473684  0.450000
2      2.0  0.473684  0.450000
3      3.0  0.473684  0.450000
4      4.0  0.500000  0.452632
5      5.0  0.500000  0.457895
6      6.0  0.500000  0.463158
7      7.0  0.473684  0.465789
8      8.0  0.473684  0.471053
9      9.0  0.473684  0.476316
10    10.0  0.394737  0.473684
....
....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...