Python/Pandas: Calculating RMS in sections

Viewed 28

What is the best way to calculate the RMS of a column in sections in python/pandas. Here is a example for a better understanding what I mean:

index x x_rms
0 2
1 3 2.55
2 10
3 22 17.09
... ... ...

So 2.55 is the RMS of 2 and 3, 17.09 is the RMS of 10 and 22 and so on.

1 Answers

the following will work

import pandas as pd

df = pd.DataFrame([2,3,10,22], columns=["x"])

def rms(a, b):
    # return round(np.sqrt((a**2+b**2)/2), 2) # for only two decimals
    return np.sqrt((a**2+b**2)/2)

df["rms"] = [rms(df.loc[idx-1,"x"], val["x"]) if idx%2 != 0 else np.nan 
             for idx, val in df.iterrows()]

output

    x   rms
0   2   NaN
1   3   2.549510
2   10  NaN
3   22  17.088007

EDIT regarding comment

if your index is a date you should do this to have the same output

values = [2,3,10,22]
tidx = pd.date_range('2019-01-01', periods=len(values), freq='D') 
df = pd.DataFrame([2,3,10,22], columns=["x"], index=tidx)

def rms(a, b):
    # return round(np.sqrt((a**2+b**2)/2), 2) # for only two decimals
    return np.sqrt((a**2+b**2)/2)

df = df.reset_index()
df["rms"] = [rms(df.loc[idx-1,"x"], val["x"]) if idx%2 != 0 else np.nan 
             for idx, val in df.iterrows()]
df.set_index("index")
Related