Home > Software design >  stepify / grid snap function for numerical array in python
stepify / grid snap function for numerical array in python

Time:09-29

Is there a function in python, numpy, pandas etc. to round a numpy array or pandas Series to certain steps like Godot's stepify does?

float stepify ( float s, float step )

Snaps float value s to a given step. This can also be used to round a floating point number to an arbitrary number of decimals.

stepify(100, 32) # Returns 96.0

stepify(3.14159, 0.01) # Returns 3.14

I've asked "round float values to interval limits / grid" already sometime ago where the grid points are non-equally distributed. This one is simpler, and I feel it's simple enough that I shouldn't need to write an own function for it.

CodePudding user response:

Divide by step size, round, multiply by step size. Given data is a numpy.ndarray or pandas.Series:

data_stepped = (data / step).round() * step

Another approach is given with pandas.cut. However you don't provide a step size but the number of equal-width bins in the range of your data:

pandas.cut(data, bins) 

CodePudding user response:

You can also do, for variable a and b:

(a//b)*b

As a function:

def stepify(a,b):
    return (a//b)*b

Using mentioned values as test:

print(stepify(100, 32)) # outputs: 96
print(stepify(3.14159, 0.01)) # outputs: 3.14

Works for numpy arrays too:

print(stepify(np.array([1.2,3.4,4.5]),0.3)) # returns [1.2 3.3 4.5]

and for Pandas series:

print(stepify(pd.Series([1.2,3.4,4.5]),0.3))

# outputs:
0    1.2
1    3.3
2    4.5
dtype: float64
  • Related