m8_

Return header with loc condition

m8_
Sep 2nd, 2019
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. import pandas as pd
  2. import datetime
  3.  
  4. # set current date
  5. current_date = datetime.datetime.now()
  6.  
  7. # some data
  8. data = [[1, 'Yes','2019-08-15','2022-08-15','Yes'],
  9.         [2, 'Yes','2019-08-15','2019-08-15','No'],
  10.         [3, 'Yes','2019-08-15','2019-08-15','Yes'],
  11.         [4, 'No','','','Yes'],
  12.         [5, 'No','','2019-08-15','No'],
  13.         [6, 'Yes','2020-08-15','2019-08-15','Yes'],
  14.         [7, 'Yes','2019-08-15','2019-08-15','No'],
  15.         [8, 'Yes','2019-08-15','2019-08-15','Yes'],
  16.         [9, 'No','','2019-08-15','No'],
  17.         [10, 'Yes','2019-08-15','2019-08-15','Yes']]
  18.  
  19. # create dataframe
  20. df = pd.DataFrame(data,columns=['Cust_ID','OrderMade','OrderDate',
  21.                                 'ShipDate','OrderCategoryB'])
  22.  
  23. # list of date columns
  24. date_cols = ["OrderDate","ShipDate"]
  25.  
  26. # Convert all date columns to datetime
  27. for col in date_cols:
  28.     df[col] = pd.to_datetime(df[col], errors ="coerce")
  29.  
  30. """ Because of an additional requirement that is outside the scope of this question,
  31. date columns must be converted using a loop and not when creating the dataframe. """
  32.    
  33. # create empty dataframe
  34. future_date_df = pd.DataFrame()
  35.  
  36. # iterate and append rows where condition is true
  37. for col in date_cols:
  38.     row = df.loc[((df[col].notna()) & (df[col] > current_date))]
  39.     future_date_df = future_date_df.append(row)
  40.     future_date_df['Column Name'] = col # this returns the last col in the
  41.                                         # list and also throw "FutureWarning:
  42.                                         # Sorting because non-concatenation
  43.                                         # axis is not aligned."
Advertisement
Add Comment
Please, Sign In to add comment