|
53 | 53 | from narwhals._arrow.typing import Mask # type: ignore[attr-defined] |
54 | 54 | from narwhals._arrow.typing import Order # type: ignore[attr-defined] |
55 | 55 | from narwhals.dtypes import DType |
| 56 | + from narwhals.schema import Schema |
56 | 57 | from narwhals.typing import CompliantDataFrame |
57 | 58 | from narwhals.typing import CompliantLazyFrame |
58 | 59 | from narwhals.typing import SizeUnit |
59 | 60 | from narwhals.typing import _1DArray |
60 | 61 | from narwhals.typing import _2DArray |
61 | 62 | from narwhals.utils import Version |
| 63 | + from narwhals.utils import _FullContext |
62 | 64 |
|
63 | 65 | JoinType: TypeAlias = Literal[ |
64 | 66 | "left semi", |
@@ -91,6 +93,40 @@ def __init__( |
91 | 93 | self._version = version |
92 | 94 | validate_backend_version(self._implementation, self._backend_version) |
93 | 95 |
|
| 96 | + @classmethod |
| 97 | + def from_numpy( |
| 98 | + cls, |
| 99 | + data: _2DArray, |
| 100 | + /, |
| 101 | + *, |
| 102 | + context: _FullContext, |
| 103 | + schema: Mapping[str, DType] | Schema | Sequence[str] | None, |
| 104 | + ) -> Self: |
| 105 | + from narwhals.schema import Schema |
| 106 | + |
| 107 | + arrays = [pa.array(val) for val in data.T] |
| 108 | + if isinstance(schema, (Mapping, Schema)): |
| 109 | + native = pa.Table.from_arrays(arrays, schema=Schema(schema).to_arrow()) |
| 110 | + elif is_sequence_but_not_str(schema): |
| 111 | + native = pa.Table.from_arrays(arrays, names=list(schema)) |
| 112 | + elif schema is None: |
| 113 | + native = pa.Table.from_arrays( |
| 114 | + arrays, names=[f"column_{x}" for x in range(data.shape[1])] |
| 115 | + ) |
| 116 | + else: |
| 117 | + msg = ( |
| 118 | + "`schema` is expected to be one of the following types: " |
| 119 | + "Mapping[str, DType] | Schema | Sequence[str]. " |
| 120 | + f"Got {type(schema)}." |
| 121 | + ) |
| 122 | + raise TypeError(msg) |
| 123 | + return cls( |
| 124 | + native, |
| 125 | + backend_version=context._backend_version, |
| 126 | + version=context._version, |
| 127 | + validate_column_names=True, |
| 128 | + ) |
| 129 | + |
94 | 130 | def __narwhals_namespace__(self: Self) -> ArrowNamespace: |
95 | 131 | from narwhals._arrow.namespace import ArrowNamespace |
96 | 132 |
|
|
0 commit comments