FlattenData.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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, labels_to_ignore: list = []) -> pd.DataFrame():
  19. '''
  20. :parm data: data given in either dictionary, list or dataframe format.
  21. '''
  22. assert(isinstance(data, (list, dict, pd.DataFrame, pd.Series))),\
  23. "Parameter 'data' either be of List, Dictionary or DataFrame type"
  24. in_length=0
  25. start = time.time()
  26. index_name=None
  27. if type(data) is pd.DataFrame:
  28. in_length = len(data.columns)
  29. index_name = data.index.name
  30. return_data = self.flatten_dataframe(data, labels_to_ignore=labels_to_ignore)
  31. elif type(data) is pd.Series:
  32. data = pd.DataFrame(data)
  33. in_length = len(data.columns)
  34. return_data = self.flatten_dataframe(data, labels_to_ignore=labels_to_ignore)
  35. elif type(data) is dict:
  36. in_length = len(data)
  37. return_data = self.flatten_dict(data, labels_to_ignore=labels_to_ignore)
  38. elif type(data) is list:
  39. in_length = len(data)
  40. return_data = self.flatten_list(data, labels_to_ignore=labels_to_ignore)
  41. else:
  42. self._log.log_and_raise_warning(("Input data type '{}' is not supported").format(type(data)))
  43. return None
  44. result_dataframe = pd.DataFrame.from_dict(return_data, orient='index')
  45. if index_name is not None:
  46. result_dataframe.index.name = index_name
  47. self._log.info(('Data has been flattened, created {} columns in {} seconds').format(len(result_dataframe.columns)- in_length, time.time()-start))
  48. return result_dataframe
  49. def flatten_dataframe(self, dataframe: pd.DataFrame, incoming_key: str = None, labels_to_ignore: list = []):
  50. '''
  51. :param pd.Dataframe dataframe: dataframe containing the data to be flattened
  52. :param str incoming_key: string to be appended to the key
  53. '''
  54. assert(isinstance(dataframe, pd.DataFrame)),\
  55. "Parameter 'dataframe' be of DataFrame type"
  56. if incoming_key is not None:
  57. assert(isinstance(incoming_key, str)),\
  58. "Parameter 'incoming_key' be of String type"
  59. result_dict = {}
  60. for index, row in dataframe.iterrows():
  61. temp_result_dict = {}
  62. for key, value in row.iteritems():
  63. small_key = key
  64. if incoming_key is not None:
  65. key = incoming_key + '_' + key
  66. temp_result = {}
  67. if small_key in labels_to_ignore:
  68. temp_result_dict[key] = value
  69. else:
  70. if type(value) == list:
  71. temp_result = self.flatten_list(value, key, labels_to_ignore)
  72. elif type(value) == dict:
  73. temp_result = self.flatten_dict(value, key, labels_to_ignore)
  74. else:
  75. temp_result_dict[key] = value
  76. if len(temp_result) > 0:
  77. temp_result_dict = self.append_to_dict(temp_result_dict, temp_result)
  78. result_dict[index] = copy.deepcopy(temp_result_dict)
  79. return result_dict
  80. def flatten_dict(self, dictionary: dict, incoming_key: str = None, labels_to_ignore: list = []):
  81. '''
  82. :param dict dictionary: dictionary containing the data to be flattened
  83. :param str incoming_key: string to be appended to the key
  84. '''
  85. assert(isinstance(dictionary, dict)),\
  86. "Parameter 'dictionary' be of Dictionary type"
  87. if incoming_key is not None:
  88. assert(isinstance(incoming_key, str)),\
  89. "Parameter 'incoming_key' be of String type"
  90. result_dict = {}
  91. for key in dictionary:
  92. small_key = key
  93. temp_data = dictionary[key]
  94. if incoming_key is not None:
  95. key = incoming_key + '_' + key
  96. temp_result = {}
  97. if small_key in labels_to_ignore:
  98. result_dict[key] = temp_data
  99. else:
  100. if type(temp_data) == list:
  101. temp_result = self.flatten_list(temp_data, key, labels_to_ignore)
  102. elif type(temp_data) == dict:
  103. temp_result = self.flatten_dict(temp_data, key, labels_to_ignore)
  104. else:
  105. result_dict[key] = temp_data
  106. if len(temp_result) > 0:
  107. result_dict = self.append_to_dict(result_dict, temp_result)
  108. return result_dict
  109. def flatten_list(self, data_list: list, incoming_key: str = None, labels_to_ignore: list = []):
  110. '''
  111. :param list data_list: list containing the data to be flattened
  112. :param str incoming_key: string to be appended to the key
  113. '''
  114. assert(isinstance(data_list, list)),\
  115. "Parameter 'data_list' be of List type"
  116. if incoming_key is not None:
  117. assert(isinstance(incoming_key, str)),\
  118. "Parameter 'incoming_key' be of String type"
  119. result_dict = {}
  120. for iteration, item in enumerate(data_list):
  121. temp_dataframe = item
  122. temp_result = {}
  123. key = incoming_key
  124. if incoming_key is not None:
  125. # OEBB SPECIFIC IF STATEMENT
  126. if type(data_list[iteration]) is dict and 'stationsnummer' in data_list[iteration].keys():
  127. key = incoming_key + '_' + str(data_list[iteration]['stationsnummer'])
  128. elif type(data_list[iteration]) is dict and 'stationsnummer' in data_list[iteration].keys() and 'stage' in data_list[iteration].keys() :
  129. key = incoming_key + '_' + str(data_list[iteration]['stationsnummer']) + '_' + str(data_list[iteration]['stage'])
  130. else:
  131. key = incoming_key + '_' + str(iteration)
  132. else:
  133. key = str(iteration)
  134. if type(temp_dataframe) == list:
  135. temp_result = self.flatten_list(temp_dataframe, key, labels_to_ignore)
  136. elif type(temp_dataframe) == dict:
  137. temp_result = self.flatten_dict(temp_dataframe, key, labels_to_ignore)
  138. else:
  139. result_dict[key] = temp_dataframe
  140. if len(temp_result) > 0:
  141. result_dict = self.append_to_dict(result_dict, temp_result)
  142. return result_dict
  143. def append_to_dict(self, dictionary: dict, to_append):
  144. '''
  145. :param dict dictionary: dictionary which holds all the resulting data.
  146. :param dict to_append: data to be added to the resulting dictionary.
  147. '''
  148. assert(isinstance(dictionary, dict)),\
  149. "Parameter 'dictionary' be of Dictionary type"
  150. assert(isinstance(to_append, dict)),\
  151. "Parameter 'to_append' be of Dictionary type"
  152. for key in to_append:
  153. dictionary[key] = to_append[key]
  154. return dictionary
  155. def flatten_if_not_flat(self, data: pd.DataFrame, labels_to_ignore: list = []):
  156. for data_type in data.dtypes:
  157. if data_type == object:
  158. return self.flatten(data, labels_to_ignore=labels_to_ignore)
  159. return data