FlattenData.py 5.9 KB

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