Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. X2 X3 X4 Y Y1
  2. 01.02.2019 1 1 1
  3. 02.02.2019 2 2 0
  4. 02.02.2019 2 3 0
  5. 02.02.2019 2 1 1
  6. 03.02.2019 1 2 1
  7. 04.02.2019 2 3 0
  8. 05.02.2019 1 1 1
  9. 06.02.2019 2 2 0
  10. 07.02.2019 1 3 1
  11. 08.02.2019 2 1 1
  12. 09.02.2019 1 2 0
  13. 10.02.2019 2 3 1
  14. 11.02.2019 1 1 0
  15. 12.02.2019 2 2 1
  16. 13.02.2019 1 3 0
  17. 14.02.2019 2 1 1
  18. 15.02.2019 1 2 1
  19. 16.02.2019 2 3 0
  20. 17.02.2019 1 1 1
  21. 18.02.2019 2 2 0
  22.  
  23. filtered_X4 = df.where(condition_1 & condition_2 & condition_3)
  24.  
  25. df = filtered_X4.shift(1).rolling(window = 999999, min_periods = 1).mean()
  26.  
  27. In [122]: df
  28. Out[122]:
  29. X2 X3 X4 Y
  30. 0 2019-02-01 1 1 9
  31. 1 2019-02-02 1 2 4
  32. 2 2019-02-02 1 1 3
  33. 3 2019-02-02 1 3 4
  34. 4 2019-02-03 1 2 3
  35. 5 2019-02-04 1 3 6
  36. 6 2019-02-05 1 4 1
  37. 7 2019-02-06 1 5 7
  38. 8 2019-02-07 1 6 6
  39. 9 2019-02-08 1 1 5
  40.  
  41. def roll(df, win="5D", dt_col="X2", filter_cols=["X3","X4"],
  42. agg_func="mean", apply_col="Y", fill_value=None,
  43. verbose=0):
  44. data = []
  45. index = []
  46. for r in df.iterrows():
  47. mask = (df.index <= r[0]) & (df[dt_col] >= r[1][dt_col] - pd.to_timedelta(win))
  48. qry = " and ".join([f"{col} == {r[1][col]}" for col in filter_cols])
  49. index.append(r[0])
  50. data.append(df.loc[mask].query(qry)[apply_col].agg(agg_func))
  51. if verbose > 0:
  52. print(f"index: {r[0]}, avg: {data[-1]}", df.loc[mask].query(qry))
  53. res = pd.Series(data, index=index)
  54. if fill_value is not None:
  55. res = res.fillna(fill_value)
  56. return res
  57.  
  58. In [128]: df["Y1"] = df.pipe(func=roll, win="5D", dt_col="X2", filter_cols=["X3","X4"],
  59. agg_func="mean", apply_col="Y")
  60.  
  61. In [129]: df
  62. Out[129]:
  63. X2 X3 X4 Y Y1
  64. 0 2019-02-01 1 1 9 9.0
  65. 1 2019-02-02 1 2 6 6.0
  66. 2 2019-02-02 1 1 6 7.5 # <---
  67. 3 2019-02-02 1 3 7 7.0
  68. 4 2019-02-03 1 2 0 3.0 # <---
  69. 5 2019-02-04 1 3 7 7.0
  70. 6 2019-02-05 1 4 0 0.0
  71. 7 2019-02-06 1 5 6 6.0
  72. 8 2019-02-07 1 6 2 2.0
  73. 9 2019-02-08 1 1 7 7.0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement