Advertisement
Guest User

Untitled

a guest
Jul 20th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. import pandas as pd
  2.  
  3. def addEmpty(data, start_date, end_date, from_loc, to_loc, day=True):
  4. dates = pd.DataFrame(0, index=pd.date_range(start=start_date, end=end_date), columns=['__'])
  5. if day:
  6. dates.index = pd.MultiIndex.from_tuples([(a.year, a.month, a.day) for a in dates.index], names=['year', 'month', 'day'])
  7. else:
  8. dates.index = pd.MultiIndex.from_tuples([(a.year, a.month) for a in dates.index], names=['year', 'month'])
  9. dates.reset_index(inplace=True)
  10.  
  11. d = dict([(loc, 0) for loc in to_loc])
  12. d['from'] = from_loc
  13.  
  14. countries = pd.DataFrame(d)
  15. countries['__'] = 0
  16. empty = dates.merge(countries, how='outer')
  17. del empty['__']
  18. empty.set_index(list(data.index.names), inplace=True)
  19.  
  20. result = pd.concat([data, empty[~empty.index.isin(data.index)]], axis=0, sort=False)
  21. result.sort_index(inplace=True)
  22. return result.fillna(0)
  23.  
  24.  
  25.  
  26. data = pd.DataFrame({'year':[2018, 2018], 'month':[1, 1], 'day':[1, 2], 'from': ['a', 'b'], 'x': [1, 0], 'y': [2, 1]})
  27. data.set_index(['year', 'month', 'day', 'from'], inplace=True)
  28. print(data)
  29. allData = addEmpty(data, '1/1/2018', '1/3/2018', from_loc=['a', 'b', 'c'], to_loc=['x', 'y', 'z'])
  30. print(allData)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement