SHARE
TWEET

Untitled

a guest Jun 16th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import pandas as pd
  2. from itertools import chain
  3.  
  4.  
  5. df_1 = pd.DataFrame({
  6.         'ID' : list(chain.from_iterable([['A'] * 365, ['B'] * 365, ['C'] * 365])),
  7.         'Date' : pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist() + pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist() + pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist(),
  8.         'Value' : np.random.randn(365 * 3)
  9.         })
  10.  
  11. df_2 = pd.DataFrame({
  12.         'ID' : ['A', 'B', 'C'],
  13.         'Initial_date' : pd.to_datetime(['2018-04-24', '2018-09-22', '2018-12-12'], format = '%Y-%m-%d')
  14.         })
  15.  
  16.  
  17. df = pd.merge(df_1, df_2, how = 'left', left_on = 'ID', right_on = 'ID')
  18.      
  19. ID       Date  Value Initial_date
  20. 0  A 2018-01-01 -1.084   2018-04-24
  21. 1  A 2018-01-02  0.585   2018-04-24
  22. 2  A 2018-01-03  0.812   2018-04-24
  23. 3  A 2018-01-04 -1.115   2018-04-24
  24. 4  A 2018-01-05 -1.724   2018-04-24
  25.      
  26. df_a = df[(df['ID'] == 'A') & (df['Date'] > '2018-03-23') & (df['Date'] < '2018-05-25')]
  27.  
  28. df_b = df[(df['ID'] == 'B') & (df['Date'] > '2018-08-21') & (df['Date'] < '2018-10-23')]
  29.  
  30. df_c = df[(df['ID'] == 'C') & (df['Date'] > '2018-11-11') & (df['Date'] < '2018-12-31')]
  31.  
  32.  
  33. df_result = pd.concat([df_a, df_b, df_c])
  34.      
  35. ID       Date  Value Initial_date
  36. 82  A 2018-03-24 -1.013   2018-04-24
  37. 83  A 2018-03-25 -0.023   2018-04-24
  38. 84  A 2018-03-26 -0.053   2018-04-24
  39. 85  A 2018-03-27 -1.091   2018-04-24
  40. 86  A 2018-03-28  1.839   2018-04-24
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top