import numpy as np
def migrate_array(source_array, target_array, mapping, default_value=None):
"""
Migrates data from a source array to a target array based on a mapping.
Includes defensive checks to handle potential errors.
Args:
source_array (np.ndarray): The source array to migrate data from.
target_array (np.ndarray): The target array to migrate data to.
mapping (dict): A dictionary where keys are source array indices/values
and values are target array indices/values.
default_value (any, optional): The value to use if a mapping is missing. Defaults to None.
Returns:
np.ndarray: The target array with migrated data. Returns the original target_array
if errors are encountered.
Raises:
TypeError: if source_array or target_array are not numpy arrays
ValueError: if mapping is not a dictionary
"""
if not isinstance(source_array, np.ndarray) or not isinstance(target_array, np.ndarray):
raise TypeError("source_array and target_array must be numpy arrays.")
if not isinstance(mapping, dict):
raise ValueError("mapping must be a dictionary.")
if source_array.shape != target_array.shape:
print("Warning: Source and target arrays have different shapes. Returning original target_array.")
return target_array
for i in range(len(source_array)):
try:
target_index = mapping[source_array[i]]
if target_index >= target_array.shape[0]:
print(f"Warning: Mapping index {target_index} is out of bounds for target array. Using default value.")
target_array[i] = default_value
else:
target_array[i] = target_array[target_index] # copy value
except KeyError:
if default_value is not None:
target_array[i] = default_value
print(f"Warning: No mapping found for value {source_array[i]}. Using default value.")
else:
print(f"Warning: No mapping found for value {source_array[i]}. Skipping.")
pass # leave the value as is.
except IndexError:
print(f"Warning: Mapping index {target_index} is out of bounds for target array. Using default value.")
target_array[i] = default_value
return target_array
Add your comment