FlattenData.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Wed Oct 9 15:17:34 2019
  5. @author: oskar
  6. @description: Class which flattens nested Dataframes, Dictionaries and Lists into tabular form
  7. """
  8. import sys
  9. import os
  10. import time
  11. import pandas as pd
  12. import copy
  13. sys.path.append(os.getcwd())
  14. from cdplib.log import Log
  15. class FlattenData():
  16. def __init__(self):
  17. self._log = Log("Flatten data")
  18. def flatten(self, data):
  19. '''
  20. :parm data: data given in either dictionary, list or dataframe format.
  21. '''
  22. assert(isinstance(data, (list, dict, pd.DataFrame))),\
  23. "Parameter 'data' either be of List, Dictionary or DataFrame type"
  24. start = time.time()
  25. if type(data) is pd.DataFrame:
  26. return_data = self.flatten_dataframe(data)
  27. self._log.info(('Data has been flattened, created {} columns in {} seconds').format(len(return_data.columns)- len(data.columns), time.time()-start))
  28. return return_data
  29. if type(data) is dict:
  30. return self.flatten_dict(data)
  31. if type(data) is list:
  32. return self.flatten_list(data)
  33. def flatten_dataframe(self, dataframe: pd.DataFrame, incoming_key: str = None):
  34. '''
  35. :param pd.Dataframe dataframe: dataframe containing the data to be flattened
  36. :param str incoming_key: string to be appended to the key
  37. '''
  38. assert(isinstance(dataframe, pd.DataFrame)),\
  39. "Parameter 'dataframe' be of DataFrame type"
  40. if incoming_key is not None:
  41. assert(isinstance(incoming_key, str)),\
  42. "Parameter 'incoming_key' be of String type"
  43. result_dict = {}
  44. for index, row in dataframe.iterrows():
  45. temp_result_dict = {}
  46. for key, value in row.iteritems():
  47. temp_result = {}
  48. if incoming_key is not None:
  49. key = incoming_key + '_' + key
  50. if type(value) == list:
  51. temp_result = self.flatten_list(value, key)
  52. elif type(value) == dict:
  53. temp_result = self.flatten_dict(value, key)
  54. else:
  55. temp_result_dict[key] = value
  56. if len(temp_result) > 0:
  57. temp_result_dict = self.append_to_dict(temp_result_dict, temp_result)
  58. result_dict[index] = copy.deepcopy(temp_result_dict)
  59. result_dataframe = pd.DataFrame.from_dict(result_dict, orient='index')
  60. return result_dataframe
  61. def flatten_dict(self, dictionary: dict, incoming_key: str = None):
  62. '''
  63. :param dict dictionary: dictionary containing the data to be flattened
  64. :param str incoming_key: string to be appended to the key
  65. '''
  66. assert(isinstance(dictionary, dict)),\
  67. "Parameter 'dictionary' be of Dictionary type"
  68. if incoming_key is not None:
  69. assert(isinstance(incoming_key, str)),\
  70. "Parameter 'incoming_key' be of String type"
  71. result_dict = {}
  72. for key in dictionary:
  73. temp_dataframe = dictionary[key]
  74. temp_result = {}
  75. if incoming_key is not None:
  76. key = incoming_key + '_' + key
  77. if type(temp_dataframe) == list:
  78. temp_result = self.flatten_list(temp_dataframe, key)
  79. elif type(temp_dataframe) == dict:
  80. temp_result = self.flatten_dict(temp_dataframe, key)
  81. else:
  82. result_dict[key] = temp_dataframe
  83. if len(temp_result) > 0:
  84. result_dict = self.append_to_dict(result_dict, temp_result)
  85. return result_dict
  86. def flatten_list(self, data_list: list, incoming_key: str = None):
  87. '''
  88. :param list data_list: list containing the data to be flattened
  89. :param str incoming_key: string to be appended to the key
  90. '''
  91. assert(isinstance(data_list, list)),\
  92. "Parameter 'data_list' be of List type"
  93. if incoming_key is not None:
  94. assert(isinstance(incoming_key, str)),\
  95. "Parameter 'incoming_key' be of String type"
  96. result_dict = {}
  97. for iteration, item in enumerate(data_list):
  98. temp_dataframe = item
  99. temp_result = {}
  100. key = incoming_key
  101. if incoming_key is not None:
  102. # OEBB SPECIFIC IF STATEMENT
  103. if type(data_list[iteration]) is dict:
  104. if 'stationsnummer' in data_list[iteration].keys() and 'stage' in data_list[iteration].keys() :
  105. key = incoming_key + '_' + str(data_list[iteration]['stationsnummer']) + '_' + str(data_list[iteration]['stage'])
  106. else:
  107. key = incoming_key + '_' + str(iteration)
  108. else:
  109. key = str(iteration)
  110. if type(temp_dataframe) == list:
  111. temp_result = self.flatten_list(temp_dataframe, key)
  112. elif type(temp_dataframe) == dict:
  113. temp_result = self.flatten_dict(temp_dataframe, key)
  114. else:
  115. result_dict[key] = temp_dataframe
  116. if len(temp_result) > 0:
  117. result_dict = self.append_to_dict(result_dict, temp_result)
  118. return result_dict
  119. def append_to_dict(self, dictionary: dict, to_append):
  120. '''
  121. :param dict dictionary: dictionary which holds all the resulting data.
  122. :param dict to_append: data to be added to the resulting dictionary.
  123. '''
  124. assert(isinstance(dictionary, dict)),\
  125. "Parameter 'dictionary' be of Dictionary type"
  126. assert(isinstance(to_append, dict)),\
  127. "Parameter 'to_append' be of Dictionary type"
  128. for key in to_append:
  129. dictionary[key] = to_append[key]
  130. return dictionary