Let's say I have a data frame that looks like that:
Result
0.001
0.000
-0.001
0.005
0.002
0.003
0.004
0.001
3.400
3.401
3.405
3.402
0.003
0.004
0.001
4.670
-0.001
4.675
4.672
0.003
3.404
I would like to group values by some interval (let's say ±0.005 from first 'not already existing' value), so here I would have it grouped as:
Result GROUP_AVG
0.001 0.003
0.000 0.003
-0.001 0.003
0.005 0.003
0.002 0.003
0.003 0.003
0.004 0.003
0.001 0.003
3.400 3.403
3.401 3.403
3.405 3.403
3.402 3.403
0.003 0.003
0.004 0.003
0.001 0.003
4.670 4.673
-0.001 0.003
4.675 4.673
4.672 4.673
0.003 0.003
3.404 3.403
Now, I am doing it inefficient way:
- Check if
row_valueis in ±0.005 from any item fromaverages_set["value"] - If no, create new entity in
averages_setwith"value": row_value, "average": row_value, count: 1 - If yes, update
averages_set[i]["average"]=(average * count + row_value)/(count+1), and alsocount=count+1 - After all the rows are iterated, add column to basic dataset and change it for each row based on its distance to
averages_set[i]["value"], change the new column value for row withaverages_set[i]["average"]as I need to have average anyway for further operations. And the average can be actually treated as discrete value without bigger problems for further operations.
I have used pandas.groupby before, and it works great for discrete values. Is there a way to, for example, group by based on float value, taking into account e.g. ±0.5 from the first new value that occurred? It was much more efficient than my algorithm, and I could easily calculate average(and not only) for each group.