Advertisement
Guest User

Untitled

a guest
Jul 20th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 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.drop_duplicates(inplace=True)
  10. dates.reset_index(inplace=True)
  11.  
  12. d = dict([(loc, 0) for loc in to_loc])
  13. d['from'] = from_loc
  14.  
  15. countries = pd.DataFrame(d)
  16. countries['__'] = 0
  17. empty = dates.merge(countries, how='outer')
  18. del empty['__']
  19. empty.set_index(list(data.index.names), inplace=True)
  20.  
  21. result = pd.concat([data, empty[~empty.index.isin(data.index)]], axis=0, sort=False)
  22. result.sort_index(inplace=True)
  23. return result.fillna(0)
  24.  
  25.  
  26.  
  27. data = pd.DataFrame({'year':[2018, 2018], 'month':[1, 1], 'day':[1, 2], 'from': ['a', 'b'], 'x': [1, 0], 'y': [2, 1]})
  28. data.set_index(['year', 'month', 'day', 'from'], inplace=True)
  29. print('Data:\n', data)
  30. allData = addEmpty(data, '1/1/2018', '1/3/2018', from_loc=['a', 'b', 'c'], to_loc=['x', 'y', 'z'])
  31. print('----------------------------------------\nAll data:\n', allData)
  32.  
  33. monthData = data.reset_index().set_index(['year', 'month', 'from'])
  34. del monthData['day']
  35. print('----------------------------------------\nMonthly data:\n', monthData)
  36. allMonthData = addEmpty(monthData, '1/1/2018', '1/3/2018', from_loc=['a', 'b', 'c'], to_loc=['x', 'y', 'z'], day=False)
  37. print('----------------------------------------\nAll monthly data:\n', allMonthData)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement