RJF
RJF

Reputation: 447

Pandas: set sliding window to iterate over rows and apply a function

I have the following DataFramein pandas:

[A]             [measure]
17442.77000     32.792658
17442.8         name1
17442.95100     32.792658
--
--
17517.49200     37.648482
17517.5         name2
17518.29600     37.648482
--
--
17565.77600     38.287118
17565.8         name3
17565.88800     38.287118
--
--
17596.93700     41.203340
17597.2         name4
17597.29700     41.203340
--
--
17602.16400     41.477979
17602.5         name5
17602.83900     41.612774
--
--
17618.16400     42.479890
17618.4         name6
17618.71100     42.681591

I'd like to iterate over every three rows and apply a function that:

f(x)= df.iloc[0,1]+(df.iloc[2,1]-df.loc[0,1])*((df.iloc[1,0]-df.iloc[0,0])/(df.iloc[2,0]-df.iloc[0,0])).

Ideally I'd like to return the result in a dictionary format so I could have:

Results={"name1": f(x), "name2": f(x),...}

Any hints about how to set my sliding windows in pandas is much appreciated.

Upvotes: 4

Views: 2212

Answers (1)

Joe
Joe

Reputation: 12417

If I understood you correctly, this should work:

def f(x):
    return df.iloc[0,1]+(df.iloc[2,1]-df.iloc[0,1])*((df.iloc[1,0]-df.iloc[0,0])/(df.iloc[2,0]-df.iloc[0,0]))

Here you apply rolling with a window=3 and min_periods=1 with a step of 3 using [[::3]]

a = df.rolling(window=3, min_periods=1).apply(f)[::3].reset_index(drop=True)

After you save the strings of the column measurement to a list s

s = list(i for i in df['measure'] if isinstance(i, basestring))

And assign s as key of the dictionary d

d = a.T.to_dict('list')
for index, k in enumerate(list(s)):
    d[k] = d[index]
    del d[index]

Upvotes: 3

Related Questions