Advertisement
Guest User

Untitled

a guest
Feb 6th, 2019
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3. from pprint import pprint
  4.  
  5.  
  6.  
  7.  
  8. df_dict = {
  9.     'A': [1, 2, 3, 4, 5],
  10.     'B': [5, 2, 3, 1, 5],
  11.     'out': np.nan
  12. }
  13. length = 2
  14. weight = 5
  15.  
  16.  
  17. def transform(row):
  18.  
  19.     row_num = int(row.name)
  20.     out = row['A'] / length
  21.  
  22.     if (row_num >= length):
  23.         previous_out = df.at[ row_num-1, 'out' ]
  24.         out = (row['B'] - previous_out) * weight + previous_out
  25.  
  26.     df.at[row_num, 'out'] = out
  27.  
  28.  
  29. df = pd.DataFrame(df_dict)
  30. df.apply( lambda x: transform(x), axis=1)
  31.  
  32. pprint(df)
  33.  
  34. # Correct output / breakdown / explaantion
  35.    A  B    out
  36. # 0  1  5    0.5  
  37. # out = a / b
  38.  
  39. # 1  2  2    1.0
  40. # out = a / b
  41.  
  42. # row_num >= length:
  43.  
  44. # 2  3  3   11.0
  45. # out = (b - previous_out) * weight + previous_out
  46. # out = (3 - 1) * 5 + 1  = 11
  47.  
  48. # 3  4  1  -39.0
  49. # out = (1 - 11) * 5 + 11 = 39
  50.  
  51. # 4  5  5  181.0
  52. # out = (5 - (-39)) * 5 + (-39) = 181
  53.  
  54.  
  55. df = pd.DataFrame(df_dict)
  56.  
  57. #  out = row['A'] / length
  58. df['out'] = df['A'] / length
  59.  
  60. # if (row_num >= length):
  61. #   previous_out = df.at[ row_num-1, 'out' ]
  62. #   out = (row['B'] - previous_out) * weight + previous_out
  63. #  df[length:]['out'] = (df[length:]['B'] - df[length:]['out'].shift() ) * weight + df[length:]['out'].shift()
  64.  
  65.  
  66. pprint(df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement