Convert an array-like value into a read-only numpy array Parameters ---------- v : array like Array like value (list, tuple, numpy array, pandas series, etc.) kind : str or tuple of str If specified, the numpy dtype kind (or kinds) that the array should
(v, kind=None, force_numeric=False)
| 65 | |
| 66 | |
| 67 | def copy_to_readonly_numpy_array(v, kind=None, force_numeric=False): |
| 68 | """ |
| 69 | Convert an array-like value into a read-only numpy array |
| 70 | |
| 71 | Parameters |
| 72 | ---------- |
| 73 | v : array like |
| 74 | Array like value (list, tuple, numpy array, pandas series, etc.) |
| 75 | kind : str or tuple of str |
| 76 | If specified, the numpy dtype kind (or kinds) that the array should |
| 77 | have, or be converted to if possible. |
| 78 | If not specified then let numpy infer the datatype |
| 79 | force_numeric : bool |
| 80 | If true, raise an exception if the resulting numpy array does not |
| 81 | have a numeric dtype (i.e. dtype.kind not in ['u', 'i', 'f']) |
| 82 | Returns |
| 83 | ------- |
| 84 | np.ndarray |
| 85 | Numpy array with the 'WRITEABLE' flag set to False |
| 86 | """ |
| 87 | np = get_module("numpy") |
| 88 | |
| 89 | assert np is not None |
| 90 | |
| 91 | # ### Process kind ### |
| 92 | if not kind: |
| 93 | kind = () |
| 94 | elif isinstance(kind, str): |
| 95 | kind = (kind,) |
| 96 | |
| 97 | first_kind = kind[0] if kind else None |
| 98 | |
| 99 | # u: unsigned int, i: signed int, f: float |
| 100 | numeric_kinds = {"u", "i", "f"} |
| 101 | kind_default_dtypes = { |
| 102 | "u": "uint32", |
| 103 | "i": "int32", |
| 104 | "f": "float64", |
| 105 | "O": "object", |
| 106 | } |
| 107 | |
| 108 | # With `pass_through=True`, the original object will be returned if unable to convert |
| 109 | # to a Narwhals DataFrame or Series. |
| 110 | v = nw.from_native(v, allow_series=True, pass_through=True) |
| 111 | |
| 112 | if isinstance(v, nw.Series): |
| 113 | if v.dtype == nw.Datetime and v.dtype.time_zone is not None: |
| 114 | # Remove time zone so that local time is displayed |
| 115 | v = v.dt.replace_time_zone(None).to_numpy() |
| 116 | else: |
| 117 | v = v.to_numpy() |
| 118 | elif isinstance(v, nw.DataFrame): |
| 119 | schema = v.schema |
| 120 | overrides = {} |
| 121 | for key, val in schema.items(): |
| 122 | if val == nw.Datetime and val.time_zone is not None: |
| 123 | # Remove time zone so that local time is displayed |
| 124 | overrides[key] = nw.col(key).dt.replace_time_zone(None) |
no test coverage detected