Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- import numpy as np
- from pprint import pprint
- df_dict = {
- 'A': [1, 2, 3, 4, 5],
- 'B': [5, 2, 3, 1, 5],
- 'out': np.nan
- }
- length = 2
- weight = 5
- def transform(row):
- row_num = int(row.name)
- out = row['A'] / length
- if (row_num >= length):
- previous_out = df.at[ row_num-1, 'out' ]
- out = (row['B'] - previous_out) * weight + previous_out
- df.at[row_num, 'out'] = out
- df = pd.DataFrame(df_dict)
- df.apply( lambda x: transform(x), axis=1)
- pprint(df)
- # Correct output / breakdown / explaantion
- A B out
- # 0 1 5 0.5
- # out = a / b
- # 1 2 2 1.0
- # out = a / b
- # row_num >= length:
- # 2 3 3 11.0
- # out = (b - previous_out) * weight + previous_out
- # out = (3 - 1) * 5 + 1 = 11
- # 3 4 1 -39.0
- # out = (1 - 11) * 5 + 11 = 39
- # 4 5 5 181.0
- # out = (5 - (-39)) * 5 + (-39) = 181
- df = pd.DataFrame(df_dict)
- # out = row['A'] / length
- df['out'] = df['A'] / length
- # if (row_num >= length):
- # previous_out = df.at[ row_num-1, 'out' ]
- # out = (row['B'] - previous_out) * weight + previous_out
- # df[length:]['out'] = (df[length:]['B'] - df[length:]['out'].shift() ) * weight + df[length:]['out'].shift()
- pprint(df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement