1. import numpy as np
  2. def convert_array(input_array, target_type='float64', min_value=None, max_value=None):
  3. """
  4. Converts an input array to a specified data type and performs sanity checks.
  5. Args:
  6. input_array (array-like): The array to convert. Can be a list, tuple, or numpy array.
  7. target_type (str): The desired data type (e.g., 'float64', 'int32', 'float32').
  8. min_value (float, optional): Minimum acceptable value for float types. Defaults to None.
  9. max_value (float, optional): Maximum acceptable value for float types. Defaults to None.
  10. Returns:
  11. numpy.ndarray: The converted numpy array, or None if conversion fails or sanity checks fail.
  12. Raises:
  13. TypeError: If input is not array-like.
  14. ValueError: If target_type is invalid.
  15. """
  16. try:
  17. # Convert to numpy array for easier handling
  18. arr = np.array(input_array)
  19. # Convert to the target data type
  20. if target_type == 'float64':
  21. arr = arr.astype(np.float64)
  22. elif target_type == 'float32':
  23. arr = arr.astype(np.float32)
  24. elif target_type == 'int32':
  25. arr = arr.astype(np.int32)
  26. elif target_type == 'int64':
  27. arr = arr.astype(np.int64)
  28. else:
  29. raise ValueError("Invalid target_type. Choose from 'float64', 'float32', 'int32', 'int64'.")
  30. # Sanity checks for float types
  31. if np.issubdtype(arr.dtype, np.floating):
  32. if min_value is not None and np.any(arr < min_value):
  33. print(f"Sanity check failed: Value below minimum ({min_value}) found.")
  34. return None
  35. if max_value is not None and np.any(arr > max_value):
  36. print(f"Sanity check failed: Value above maximum ({max_value}) found.")
  37. return None
  38. return arr
  39. except TypeError:
  40. print("Error: Input must be array-like.")
  41. return None
  42. except ValueError as e:
  43. print(f"Error: {e}")
  44. return None
  45. except Exception as e:
  46. print(f"An unexpected error occurred: {e}")
  47. return None
  48. if __name__ == '__main__':
  49. # Example Usage
  50. data = [1, 2, 3.5, 4, 5]
  51. converted_array = convert_array(data, target_type='float64', min_value=2.0, max_value=4.0)
  52. if converted_array is not None:
  53. print("Converted array:", converted_array)
  54. data2 = [1, 2, 3, 4, 5]
  55. converted_array2 = convert_array(data2, target_type='int32')
  56. if converted_array2 is not None:
  57. print("Converted array:", converted_array2)
  58. data3 = [1, 2, 3, 4, 5]
  59. converted_array3 = convert_array(data3, target_type='invalid_type')
  60. if converted_array3 is not None:
  61. print("Converted array:", converted_array3)

Add your comment