🔍 Code Extractor

function asarray

Maturity: 44

Converts array-like objects (lists, pandas Series, objects with __array__ method) to NumPy ndarray format with optional strict validation.

File:
/tf/active/vicechatdev/patches/util.py
Lines:
815 - 830
Complexity:
simple

Purpose

This utility function provides a unified interface for converting various array-like data structures into NumPy arrays. It handles multiple input types including native NumPy arrays (pass-through), Python lists, pandas-like objects with a .values attribute, and any object implementing the __array__ protocol. The strict parameter controls whether to raise an error or return the original object when conversion is not possible.

Source Code

def asarray(arraylike, strict=True):
    """
    Converts arraylike objects to NumPy ndarray types. Errors if
    object is not arraylike and strict option is enabled.
    """
    if isinstance(arraylike, np.ndarray):
        return arraylike
    elif isinstance(arraylike, list):
        return np.asarray(arraylike, dtype=object)
    elif not isinstance(arraylike, np.ndarray) and isinstance(arraylike, arraylike_types):
        return arraylike.values
    elif hasattr(arraylike, '__array__'):
        return np.asarray(arraylike)
    elif strict:
        raise ValueError('Could not convert %s type to array' % type(arraylike))
    return arraylike

Parameters

Name Type Default Kind
arraylike - - positional_or_keyword
strict - True positional_or_keyword

Parameter Details

arraylike: The input object to convert to a NumPy array. Can be a numpy.ndarray (returned as-is), a Python list (converted to object dtype array), an object with a .values attribute (like pandas Series/DataFrame), or any object implementing the __array__ protocol. If strict=False, can be any type.

strict: Boolean flag (default: True) that controls error handling. When True, raises ValueError if the input cannot be converted to an array. When False, returns the original object unchanged if conversion fails.

Return Value

Returns a numpy.ndarray in most cases. If input is already a numpy.ndarray, returns it unchanged. Lists are converted to object dtype arrays. Objects with .values attribute return that attribute (typically numpy.ndarray). Objects with __array__ method are converted via np.asarray(). If strict=False and conversion fails, returns the original input object unchanged.

Dependencies

  • numpy

Required Imports

import numpy as np

Usage Example

import numpy as np

def asarray(arraylike, strict=True):
    if isinstance(arraylike, np.ndarray):
        return arraylike
    elif isinstance(arraylike, list):
        return np.asarray(arraylike, dtype=object)
    elif not isinstance(arraylike, np.ndarray) and isinstance(arraylike, arraylike_types):
        return arraylike.values
    elif hasattr(arraylike, '__array__'):
        return np.asarray(arraylike)
    elif strict:
        raise ValueError('Could not convert %s type to array' % type(arraylike))
    return arraylike

# Example 1: Convert list to array
result = asarray([1, 2, 3, 4])
print(result)  # [1 2 3 4]

# Example 2: Pass through existing numpy array
arr = np.array([5, 6, 7])
result = asarray(arr)
print(result is arr)  # True (same object)

# Example 3: Non-strict mode with unconvertible object
result = asarray({'key': 'value'}, strict=False)
print(result)  # {'key': 'value'} (original object returned)

# Example 4: Strict mode with unconvertible object (raises error)
try:
    result = asarray({'key': 'value'}, strict=True)
except ValueError as e:
    print(f'Error: {e}')  # Error: Could not convert <class 'dict'> type to array

Best Practices

  • Use strict=True (default) when you need to ensure the result is always a numpy array, as it will raise an error for unconvertible types
  • Use strict=False when working with heterogeneous data where some objects may not be convertible and you want to preserve them as-is
  • Note that the function references 'arraylike_types' which is not defined in the provided code - ensure this variable is defined in the module scope before using this function
  • Lists are converted to object dtype arrays, which may have performance implications for numeric operations - consider using explicit dtype conversion if needed
  • The function checks for .values attribute which is common in pandas objects, making it useful for pandas-numpy interoperability
  • Objects implementing __array__ protocol are automatically handled, making this function compatible with many scientific Python libraries

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function numpy_scalar_to_python 58.1% similar

    Converts NumPy scalar types to their equivalent native Python types (float or int), returning the original value if it's not a NumPy numeric scalar.

    From: /tf/active/vicechatdev/patches/util.py
  • function clean_for_json_v10 54.7% similar

    Recursively converts Python objects containing NumPy and Pandas data types into JSON-serializable native Python types.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/c385e1f5-fbf6-4832-8fd4-78ef8b72fc53/project_1/analysis.py
  • function is_cupy_array 53.9% similar

    Checks whether the provided data object is a CuPy ndarray by conditionally importing CuPy and performing an isinstance check.

    From: /tf/active/vicechatdev/patches/util.py
  • function clean_for_json_v3 53.1% similar

    Recursively converts Python objects (including NumPy and Pandas types) into JSON-serializable formats by handling special numeric types, NaN/Inf values, and nested data structures.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/f0a78968-1d2b-4fbe-a0c6-a372da2ce2a4/project_1/analysis.py
  • function is_dask_array 50.9% similar

    Checks whether the provided data object is a Dask array by conditionally importing dask.array and performing an isinstance check.

    From: /tf/active/vicechatdev/patches/util.py
← Back to Browse