import numpy as np
def convert_array(input_array, target_type='float64', min_value=None, max_value=None):
"""
Converts an input array to a specified data type and performs sanity checks.
Args:
input_array (array-like): The array to convert. Can be a list, tuple, or numpy array.
target_type (str): The desired data type (e.g., 'float64', 'int32', 'float32').
min_value (float, optional): Minimum acceptable value for float types. Defaults to None.
max_value (float, optional): Maximum acceptable value for float types. Defaults to None.
Returns:
numpy.ndarray: The converted numpy array, or None if conversion fails or sanity checks fail.
Raises:
TypeError: If input is not array-like.
ValueError: If target_type is invalid.
"""
try:
# Convert to numpy array for easier handling
arr = np.array(input_array)
# Convert to the target data type
if target_type == 'float64':
arr = arr.astype(np.float64)
elif target_type == 'float32':
arr = arr.astype(np.float32)
elif target_type == 'int32':
arr = arr.astype(np.int32)
elif target_type == 'int64':
arr = arr.astype(np.int64)
else:
raise ValueError("Invalid target_type. Choose from 'float64', 'float32', 'int32', 'int64'.")
# Sanity checks for float types
if np.issubdtype(arr.dtype, np.floating):
if min_value is not None and np.any(arr < min_value):
print(f"Sanity check failed: Value below minimum ({min_value}) found.")
return None
if max_value is not None and np.any(arr > max_value):
print(f"Sanity check failed: Value above maximum ({max_value}) found.")
return None
return arr
except TypeError:
print("Error: Input must be array-like.")
return None
except ValueError as e:
print(f"Error: {e}")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
if __name__ == '__main__':
# Example Usage
data = [1, 2, 3.5, 4, 5]
converted_array = convert_array(data, target_type='float64', min_value=2.0, max_value=4.0)
if converted_array is not None:
print("Converted array:", converted_array)
data2 = [1, 2, 3, 4, 5]
converted_array2 = convert_array(data2, target_type='int32')
if converted_array2 is not None:
print("Converted array:", converted_array2)
data3 = [1, 2, 3, 4, 5]
converted_array3 = convert_array(data3, target_type='invalid_type')
if converted_array3 is not None:
print("Converted array:", converted_array3)
Add your comment