1. import numpy as np
  2. def migrate_array(source_array, target_array, mapping, default_value=None):
  3. """
  4. Migrates data from a source array to a target array based on a mapping.
  5. Includes defensive checks to handle potential errors.
  6. Args:
  7. source_array (np.ndarray): The source array to migrate data from.
  8. target_array (np.ndarray): The target array to migrate data to.
  9. mapping (dict): A dictionary where keys are source array indices/values
  10. and values are target array indices/values.
  11. default_value (any, optional): The value to use if a mapping is missing. Defaults to None.
  12. Returns:
  13. np.ndarray: The target array with migrated data. Returns the original target_array
  14. if errors are encountered.
  15. Raises:
  16. TypeError: if source_array or target_array are not numpy arrays
  17. ValueError: if mapping is not a dictionary
  18. """
  19. if not isinstance(source_array, np.ndarray) or not isinstance(target_array, np.ndarray):
  20. raise TypeError("source_array and target_array must be numpy arrays.")
  21. if not isinstance(mapping, dict):
  22. raise ValueError("mapping must be a dictionary.")
  23. if source_array.shape != target_array.shape:
  24. print("Warning: Source and target arrays have different shapes. Returning original target_array.")
  25. return target_array
  26. for i in range(len(source_array)):
  27. try:
  28. target_index = mapping[source_array[i]]
  29. if target_index >= target_array.shape[0]:
  30. print(f"Warning: Mapping index {target_index} is out of bounds for target array. Using default value.")
  31. target_array[i] = default_value
  32. else:
  33. target_array[i] = target_array[target_index] # copy value
  34. except KeyError:
  35. if default_value is not None:
  36. target_array[i] = default_value
  37. print(f"Warning: No mapping found for value {source_array[i]}. Using default value.")
  38. else:
  39. print(f"Warning: No mapping found for value {source_array[i]}. Skipping.")
  40. pass # leave the value as is.
  41. except IndexError:
  42. print(f"Warning: Mapping index {target_index} is out of bounds for target array. Using default value.")
  43. target_array[i] = default_value
  44. return target_array

Add your comment