kumoai 2.13.0.dev202511231731__cp312-cp312-macosx_11_0_arm64.whl → 2.13.0.dev202512031731__cp312-cp312-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. kumoai/_version.py +1 -1
  2. kumoai/connector/utils.py +23 -2
  3. kumoai/experimental/rfm/__init__.py +20 -45
  4. kumoai/experimental/rfm/backend/__init__.py +0 -0
  5. kumoai/experimental/rfm/backend/local/__init__.py +38 -0
  6. kumoai/experimental/rfm/backend/local/table.py +95 -0
  7. kumoai/experimental/rfm/backend/snow/__init__.py +35 -0
  8. kumoai/experimental/rfm/backend/snow/table.py +95 -0
  9. kumoai/experimental/rfm/backend/sqlite/__init__.py +30 -0
  10. kumoai/experimental/rfm/backend/sqlite/table.py +94 -0
  11. kumoai/experimental/rfm/base/__init__.py +10 -0
  12. kumoai/experimental/rfm/base/column.py +66 -0
  13. kumoai/experimental/rfm/base/source.py +18 -0
  14. kumoai/experimental/rfm/{local_table.py → base/table.py} +134 -139
  15. kumoai/experimental/rfm/{local_graph.py → graph.py} +229 -62
  16. kumoai/experimental/rfm/infer/__init__.py +6 -0
  17. kumoai/experimental/rfm/infer/dtype.py +90 -0
  18. kumoai/experimental/rfm/infer/pkey.py +126 -0
  19. kumoai/experimental/rfm/infer/time_col.py +62 -0
  20. kumoai/experimental/rfm/local_graph_sampler.py +42 -1
  21. kumoai/experimental/rfm/local_graph_store.py +13 -27
  22. kumoai/experimental/rfm/rfm.py +16 -17
  23. kumoai/experimental/rfm/sagemaker.py +11 -3
  24. kumoai/testing/decorators.py +1 -1
  25. {kumoai-2.13.0.dev202511231731.dist-info → kumoai-2.13.0.dev202512031731.dist-info}/METADATA +8 -8
  26. {kumoai-2.13.0.dev202511231731.dist-info → kumoai-2.13.0.dev202512031731.dist-info}/RECORD +29 -17
  27. kumoai/experimental/rfm/utils.py +0 -344
  28. {kumoai-2.13.0.dev202511231731.dist-info → kumoai-2.13.0.dev202512031731.dist-info}/WHEEL +0 -0
  29. {kumoai-2.13.0.dev202511231731.dist-info → kumoai-2.13.0.dev202512031731.dist-info}/licenses/LICENSE +0 -0
  30. {kumoai-2.13.0.dev202511231731.dist-info → kumoai-2.13.0.dev202512031731.dist-info}/top_level.txt +0 -0
@@ -2,8 +2,10 @@ import contextlib
2
2
  import io
3
3
  import warnings
4
4
  from collections import defaultdict
5
+ from dataclasses import dataclass, field
5
6
  from importlib.util import find_spec
6
- from typing import TYPE_CHECKING, Dict, List, Optional, Union
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
7
9
 
8
10
  import pandas as pd
9
11
  from kumoapi.graph import ColumnKey, ColumnKeyGroup, GraphDefinition
@@ -12,19 +14,28 @@ from kumoapi.typing import Stype
12
14
  from typing_extensions import Self
13
15
 
14
16
  from kumoai import in_notebook
15
- from kumoai.experimental.rfm import LocalTable
17
+ from kumoai.experimental.rfm import Table
16
18
  from kumoai.graph import Edge
19
+ from kumoai.mixin import CastMixin
17
20
 
18
21
  if TYPE_CHECKING:
19
22
  import graphviz
23
+ from adbc_driver_sqlite.dbapi import AdbcSqliteConnection
24
+ from snowflake.connector import SnowflakeConnection
20
25
 
21
26
 
22
- class LocalGraph:
23
- r"""A graph of :class:`LocalTable` objects, akin to relationships between
27
+ @dataclass
28
+ class SqliteConnectionConfig(CastMixin):
29
+ uri: Union[str, Path]
30
+ kwargs: Dict[str, Any] = field(default_factory=dict)
31
+
32
+
33
+ class Graph:
34
+ r"""A graph of :class:`Table` objects, akin to relationships between
24
35
  tables in a relational database.
25
36
 
26
37
  Creating a graph is the final step of data definition; after a
27
- :class:`LocalGraph` is created, you can use it to initialize the
38
+ :class:`Graph` is created, you can use it to initialize the
28
39
  Kumo Relational Foundation Model (:class:`KumoRFM`).
29
40
 
30
41
  .. code-block:: python
@@ -44,7 +55,7 @@ class LocalGraph:
44
55
  >>> table3 = rfm.LocalTable(name="table3", data=df3)
45
56
 
46
57
  >>> # Create a graph from a dictionary of tables:
47
- >>> graph = rfm.LocalGraph({
58
+ >>> graph = rfm.Graph({
48
59
  ... "table1": table1,
49
60
  ... "table2": table2,
50
61
  ... "table3": table3,
@@ -75,33 +86,47 @@ class LocalGraph:
75
86
 
76
87
  def __init__(
77
88
  self,
78
- tables: List[LocalTable],
79
- edges: Optional[List[Edge]] = None,
89
+ tables: Sequence[Table],
90
+ edges: Optional[Sequence[Edge]] = None,
80
91
  ) -> None:
81
92
 
82
- self._tables: Dict[str, LocalTable] = {}
93
+ self._tables: Dict[str, Table] = {}
83
94
  self._edges: List[Edge] = []
84
95
 
85
96
  for table in tables:
86
97
  self.add_table(table)
87
98
 
99
+ for table in tables:
100
+ for fkey in table._source_foreign_key_dict.values():
101
+ if fkey.name not in table or fkey.dst_table not in self:
102
+ continue
103
+ if self[fkey.dst_table].primary_key is None:
104
+ self[fkey.dst_table].primary_key = fkey.primary_key
105
+ elif self[fkey.dst_table]._primary_key != fkey.primary_key:
106
+ raise ValueError(f"Found duplicate primary key definition "
107
+ f"'{self[fkey.dst_table]._primary_key}' "
108
+ f"and '{fkey.primary_key}' in table "
109
+ f"'{fkey.dst_table}'.")
110
+ self.link(table.name, fkey.name, fkey.dst_table)
111
+
88
112
  for edge in (edges or []):
89
113
  _edge = Edge._cast(edge)
90
114
  assert _edge is not None
91
- self.link(*_edge)
115
+ if _edge not in self._edges:
116
+ self.link(*_edge)
92
117
 
93
118
  @classmethod
94
119
  def from_data(
95
120
  cls,
96
121
  df_dict: Dict[str, pd.DataFrame],
97
- edges: Optional[List[Edge]] = None,
122
+ edges: Optional[Sequence[Edge]] = None,
98
123
  infer_metadata: bool = True,
99
124
  verbose: bool = True,
100
125
  ) -> Self:
101
- r"""Creates a :class:`LocalGraph` from a dictionary of
126
+ r"""Creates a :class:`Graph` from a dictionary of
102
127
  :class:`pandas.DataFrame` objects.
103
128
 
104
- Automatically infers table metadata and links.
129
+ Automatically infers table metadata and links by default.
105
130
 
106
131
  .. code-block:: python
107
132
 
@@ -115,55 +140,186 @@ class LocalGraph:
115
140
  >>> df3 = pd.DataFrame(...)
116
141
 
117
142
  >>> # Create a graph from a dictionary of data frames:
118
- >>> graph = rfm.LocalGraph.from_data({
143
+ >>> graph = rfm.Graph.from_data({
119
144
  ... "table1": df1,
120
145
  ... "table2": df2,
121
146
  ... "table3": df3,
122
147
  ... })
123
148
 
124
- >>> # Inspect table metadata:
125
- >>> for table in graph.tables.values():
126
- ... table.print_metadata()
127
-
128
- >>> # Visualize graph (if graphviz is installed):
129
- >>> graph.visualize()
130
-
131
149
  Args:
132
150
  df_dict: A dictionary of data frames, where the keys are the names
133
151
  of the tables and the values hold table data.
152
+ edges: An optional list of :class:`~kumoai.graph.Edge` objects to
153
+ add to the graph. If not provided, edges will be automatically
154
+ inferred from the data in case ``infer_metadata=True``.
134
155
  infer_metadata: Whether to infer metadata for all tables in the
135
156
  graph.
157
+ verbose: Whether to print verbose output.
158
+ """
159
+ from kumoai.experimental.rfm.backend.local import LocalTable
160
+ tables = [LocalTable(df, name) for name, df in df_dict.items()]
161
+
162
+ graph = cls(tables, edges=edges or [])
163
+
164
+ if infer_metadata:
165
+ graph.infer_metadata(False)
166
+
167
+ if edges is None:
168
+ graph.infer_links(False)
169
+
170
+ if verbose:
171
+ graph.print_metadata()
172
+ graph.print_links()
173
+
174
+ return graph
175
+
176
+ @classmethod
177
+ def from_sqlite(
178
+ cls,
179
+ connection: Union[
180
+ 'AdbcSqliteConnection',
181
+ SqliteConnectionConfig,
182
+ str,
183
+ Path,
184
+ Dict[str, Any],
185
+ ],
186
+ table_names: Optional[Sequence[str]] = None,
187
+ edges: Optional[Sequence[Edge]] = None,
188
+ infer_metadata: bool = True,
189
+ verbose: bool = True,
190
+ ) -> Self:
191
+ r"""Creates a :class:`Graph` from a :class:`sqlite` database.
192
+
193
+ Automatically infers table metadata and links by default.
194
+
195
+ .. code-block:: python
196
+
197
+ >>> # doctest: +SKIP
198
+ >>> import kumoai.experimental.rfm as rfm
199
+
200
+ >>> # Create a graph from a SQLite database:
201
+ >>> graph = rfm.Graph.from_sqlite('data.db')
202
+
203
+ Args:
204
+ connection: An open connection from
205
+ :meth:`~kumoai.experimental.rfm.backend.sqlite.connect` or the
206
+ path to the database file.
207
+ table_names: Set of table names to include. If ``None``, will add
208
+ all tables present in the database.
136
209
  edges: An optional list of :class:`~kumoai.graph.Edge` objects to
137
210
  add to the graph. If not provided, edges will be automatically
138
- inferred from the data.
211
+ inferred from the data in case ``infer_metadata=True``.
212
+ infer_metadata: Whether to infer metadata for all tables in the
213
+ graph.
139
214
  verbose: Whether to print verbose output.
215
+ """
216
+ from kumoai.experimental.rfm.backend.sqlite import (
217
+ Connection,
218
+ SQLiteTable,
219
+ connect,
220
+ )
221
+
222
+ if not isinstance(connection, Connection):
223
+ connection = SqliteConnectionConfig._cast(connection)
224
+ assert isinstance(connection, SqliteConnectionConfig)
225
+ connection = connect(connection.uri, **connection.kwargs)
226
+ assert isinstance(connection, Connection)
227
+
228
+ if table_names is None:
229
+ with connection.cursor() as cursor:
230
+ cursor.execute("SELECT name FROM sqlite_master "
231
+ "WHERE type='table'")
232
+ table_names = [row[0] for row in cursor.fetchall()]
233
+
234
+ tables = [SQLiteTable(connection, name) for name in table_names]
140
235
 
141
- Note:
142
- This method will automatically infer metadata and links for the
143
- graph.
236
+ graph = cls(tables, edges=edges or [])
237
+
238
+ if infer_metadata:
239
+ graph.infer_metadata(False)
240
+
241
+ if edges is None:
242
+ graph.infer_links(False)
243
+
244
+ if verbose:
245
+ graph.print_metadata()
246
+ graph.print_links()
247
+
248
+ return graph
249
+
250
+ @classmethod
251
+ def from_snowflake(
252
+ cls,
253
+ connection: Union['SnowflakeConnection', Dict[str, Any], None] = None,
254
+ table_names: Optional[Sequence[str]] = None,
255
+ edges: Optional[Sequence[Edge]] = None,
256
+ infer_metadata: bool = True,
257
+ verbose: bool = True,
258
+ ) -> Self:
259
+ r"""Creates a :class:`Graph` from a :class:`snowflake` database and
260
+ schema.
261
+
262
+ Automatically infers table metadata and links by default.
263
+
264
+ .. code-block:: python
144
265
 
145
- Example:
146
266
  >>> # doctest: +SKIP
147
267
  >>> import kumoai.experimental.rfm as rfm
148
- >>> df1 = pd.DataFrame(...)
149
- >>> df2 = pd.DataFrame(...)
150
- >>> df3 = pd.DataFrame(...)
151
- >>> graph = rfm.LocalGraph.from_data(data={
152
- ... "table1": df1,
153
- ... "table2": df2,
154
- ... "table3": df3,
155
- ... })
156
- >>> graph.validate()
268
+
269
+ >>> # Create a graph directly in a Snowflake notebook:
270
+ >>> graph = rfm.Graph.from_snowflake()
271
+
272
+ Args:
273
+ connection: An open connection from
274
+ :meth:`~kumoai.experimental.rfm.backend.snow.connect` or the
275
+ :class:`snowflake` connector keyword arguments to open a new
276
+ connection. If ``None``, will re-use an active session in case
277
+ it exists, or create a new connection from credentials stored
278
+ in environment variables.
279
+ table_names: Set of table names to include. If ``None``, will add
280
+ all tables present in the database.
281
+ edges: An optional list of :class:`~kumoai.graph.Edge` objects to
282
+ add to the graph. If not provided, edges will be automatically
283
+ inferred from the data in case ``infer_metadata=True``.
284
+ infer_metadata: Whether to infer metadata for all tables in the
285
+ graph.
286
+ verbose: Whether to print verbose output.
157
287
  """
158
- tables = [LocalTable(df, name) for name, df in df_dict.items()]
288
+ from kumoai.experimental.rfm.backend.snow import (
289
+ Connection,
290
+ SnowTable,
291
+ connect,
292
+ )
293
+
294
+ if not isinstance(connection, Connection):
295
+ connection = connect(**(connection or {}))
296
+ assert isinstance(connection, Connection)
297
+
298
+ if table_names is None:
299
+ with connection.cursor() as cursor:
300
+ cursor.execute("SELECT CURRENT_DATABASE(), CURRENT_SCHEMA()")
301
+ database, schema = cursor.fetchone()
302
+ query = f"""
303
+ SELECT TABLE_NAME
304
+ FROM {database}.INFORMATION_SCHEMA.TABLES
305
+ WHERE TABLE_SCHEMA = '{schema}'
306
+ """
307
+ cursor.execute(query)
308
+ table_names = [row[0] for row in cursor.fetchall()]
309
+
310
+ tables = [SnowTable(connection, name) for name in table_names]
159
311
 
160
312
  graph = cls(tables, edges=edges or [])
161
313
 
162
314
  if infer_metadata:
163
- graph.infer_metadata(verbose)
315
+ graph.infer_metadata(False)
164
316
 
165
317
  if edges is None:
166
- graph.infer_links(verbose)
318
+ graph.infer_links(False)
319
+
320
+ if verbose:
321
+ graph.print_metadata()
322
+ graph.print_links()
167
323
 
168
324
  return graph
169
325
 
@@ -175,7 +331,7 @@ class LocalGraph:
175
331
  """
176
332
  return name in self.tables
177
333
 
178
- def table(self, name: str) -> LocalTable:
334
+ def table(self, name: str) -> Table:
179
335
  r"""Returns the table with name ``name`` in the graph.
180
336
 
181
337
  Raises:
@@ -186,11 +342,11 @@ class LocalGraph:
186
342
  return self.tables[name]
187
343
 
188
344
  @property
189
- def tables(self) -> Dict[str, LocalTable]:
345
+ def tables(self) -> Dict[str, Table]:
190
346
  r"""Returns the dictionary of table objects."""
191
347
  return self._tables
192
348
 
193
- def add_table(self, table: LocalTable) -> Self:
349
+ def add_table(self, table: Table) -> Self:
194
350
  r"""Adds a table to the graph.
195
351
 
196
352
  Args:
@@ -199,11 +355,21 @@ class LocalGraph:
199
355
  Raises:
200
356
  KeyError: If a table with the same name already exists in the
201
357
  graph.
358
+ ValueError: If the table belongs to a different backend than the
359
+ rest of the tables in the graph.
202
360
  """
203
361
  if table.name in self._tables:
204
362
  raise KeyError(f"Cannot add table with name '{table.name}' to "
205
363
  f"this graph; table names must be globally unique.")
206
364
 
365
+ if len(self._tables) > 0:
366
+ cls = next(iter(self._tables.values())).__class__
367
+ if table.__class__ != cls:
368
+ raise ValueError(f"Cannot register a "
369
+ f"'{table.__class__.__name__}' to this "
370
+ f"graph since other tables are of type "
371
+ f"'{cls.__name__}'.")
372
+
207
373
  self._tables[table.name] = table
208
374
 
209
375
  return self
@@ -241,7 +407,7 @@ class LocalGraph:
241
407
  Example:
242
408
  >>> # doctest: +SKIP
243
409
  >>> import kumoai.experimental.rfm as rfm
244
- >>> graph = rfm.LocalGraph(tables=...).infer_metadata()
410
+ >>> graph = rfm.Graph(tables=...).infer_metadata()
245
411
  >>> graph.metadata # doctest: +SKIP
246
412
  name primary_key time_column end_time_column
247
413
  0 users user_id - -
@@ -263,7 +429,7 @@ class LocalGraph:
263
429
  })
264
430
 
265
431
  def print_metadata(self) -> None:
266
- r"""Prints the :meth:`~LocalGraph.metadata` of the graph."""
432
+ r"""Prints the :meth:`~Graph.metadata` of the graph."""
267
433
  if in_notebook():
268
434
  from IPython.display import Markdown, display
269
435
  display(Markdown('### 🗂️ Graph Metadata'))
@@ -287,7 +453,7 @@ class LocalGraph:
287
453
 
288
454
  Note:
289
455
  For more information, please see
290
- :meth:`kumoai.experimental.rfm.LocalTable.infer_metadata`.
456
+ :meth:`kumoai.experimental.rfm.Table.infer_metadata`.
291
457
  """
292
458
  for table in self.tables.values():
293
459
  table.infer_metadata(verbose=False)
@@ -305,7 +471,7 @@ class LocalGraph:
305
471
  return self._edges
306
472
 
307
473
  def print_links(self) -> None:
308
- r"""Prints the :meth:`~LocalGraph.edges` of the graph."""
474
+ r"""Prints the :meth:`~Graph.edges` of the graph."""
309
475
  edges = [(edge.dst_table, self[edge.dst_table]._primary_key,
310
476
  edge.src_table, edge.fkey) for edge in self.edges]
311
477
  edges = sorted(edges)
@@ -333,9 +499,9 @@ class LocalGraph:
333
499
 
334
500
  def link(
335
501
  self,
336
- src_table: Union[str, LocalTable],
502
+ src_table: Union[str, Table],
337
503
  fkey: str,
338
- dst_table: Union[str, LocalTable],
504
+ dst_table: Union[str, Table],
339
505
  ) -> Self:
340
506
  r"""Links two tables (``src_table`` and ``dst_table``) from the foreign
341
507
  key ``fkey`` in the source table to the primary key in the destination
@@ -358,11 +524,11 @@ class LocalGraph:
358
524
  table does not exist in the graph, if the source key does not
359
525
  exist in the source table.
360
526
  """
361
- if isinstance(src_table, LocalTable):
527
+ if isinstance(src_table, Table):
362
528
  src_table = src_table.name
363
529
  assert isinstance(src_table, str)
364
530
 
365
- if isinstance(dst_table, LocalTable):
531
+ if isinstance(dst_table, Table):
366
532
  dst_table = dst_table.name
367
533
  assert isinstance(dst_table, str)
368
534
 
@@ -396,9 +562,9 @@ class LocalGraph:
396
562
 
397
563
  def unlink(
398
564
  self,
399
- src_table: Union[str, LocalTable],
565
+ src_table: Union[str, Table],
400
566
  fkey: str,
401
- dst_table: Union[str, LocalTable],
567
+ dst_table: Union[str, Table],
402
568
  ) -> Self:
403
569
  r"""Removes an :class:`~kumoai.graph.Edge` from the graph.
404
570
 
@@ -410,11 +576,11 @@ class LocalGraph:
410
576
  Raises:
411
577
  ValueError: if the edge is not present in the graph.
412
578
  """
413
- if isinstance(src_table, LocalTable):
579
+ if isinstance(src_table, Table):
414
580
  src_table = src_table.name
415
581
  assert isinstance(src_table, str)
416
582
 
417
- if isinstance(dst_table, LocalTable):
583
+ if isinstance(dst_table, Table):
418
584
  dst_table = dst_table.name
419
585
  assert isinstance(dst_table, str)
420
586
 
@@ -428,17 +594,13 @@ class LocalGraph:
428
594
  return self
429
595
 
430
596
  def infer_links(self, verbose: bool = True) -> Self:
431
- r"""Infers links for the tables and adds them as edges to the graph.
597
+ r"""Infers missing links for the tables and adds them as edges to the
598
+ graph.
432
599
 
433
600
  Args:
434
601
  verbose: Whether to print verbose output.
435
-
436
- Note:
437
- This function expects graph edges to be undefined upfront.
438
602
  """
439
- if len(self.edges) > 0:
440
- warnings.warn("Cannot infer links if graph edges already exist")
441
- return self
603
+ known_edges = {(edge.src_table, edge.fkey) for edge in self.edges}
442
604
 
443
605
  # A list of primary key candidates (+score) for every column:
444
606
  candidate_dict: dict[
@@ -463,6 +625,9 @@ class LocalGraph:
463
625
  src_table_name = src_table.name.lower()
464
626
 
465
627
  for src_key in src_table.columns:
628
+ if (src_table.name, src_key.name) in known_edges:
629
+ continue
630
+
466
631
  if src_key == src_table.primary_key:
467
632
  continue # Cannot link to primary key.
468
633
 
@@ -528,7 +693,9 @@ class LocalGraph:
528
693
  score += 1.0
529
694
 
530
695
  # Cardinality ratio:
531
- if len(src_table._data) > len(dst_table._data):
696
+ if (src_table._num_rows is not None
697
+ and dst_table._num_rows is not None
698
+ and src_table._num_rows > dst_table._num_rows):
532
699
  score += 1.0
533
700
 
534
701
  if score < 5.0:
@@ -790,7 +957,7 @@ class LocalGraph:
790
957
  def __contains__(self, name: str) -> bool:
791
958
  return self.has_table(name)
792
959
 
793
- def __getitem__(self, name: str) -> LocalTable:
960
+ def __getitem__(self, name: str) -> Table:
794
961
  return self.table(name)
795
962
 
796
963
  def __delitem__(self, name: str) -> None:
@@ -1,9 +1,15 @@
1
+ from .dtype import infer_dtype
2
+ from .pkey import infer_primary_key
3
+ from .time_col import infer_time_column
1
4
  from .id import contains_id
2
5
  from .timestamp import contains_timestamp
3
6
  from .categorical import contains_categorical
4
7
  from .multicategorical import contains_multicategorical
5
8
 
6
9
  __all__ = [
10
+ 'infer_dtype',
11
+ 'infer_primary_key',
12
+ 'infer_time_column',
7
13
  'contains_id',
8
14
  'contains_timestamp',
9
15
  'contains_categorical',
@@ -0,0 +1,90 @@
1
+ from typing import Any, Dict
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import pyarrow as pa
6
+ from kumoapi.typing import Dtype
7
+
8
+ PANDAS_TO_DTYPE: Dict[Any, Dtype] = {
9
+ np.dtype('bool'): Dtype.bool,
10
+ pd.BooleanDtype(): Dtype.bool,
11
+ pa.bool_(): Dtype.bool,
12
+ np.dtype('byte'): Dtype.int,
13
+ pd.UInt8Dtype(): Dtype.int,
14
+ np.dtype('int16'): Dtype.int,
15
+ pd.Int16Dtype(): Dtype.int,
16
+ np.dtype('int32'): Dtype.int,
17
+ pd.Int32Dtype(): Dtype.int,
18
+ np.dtype('int64'): Dtype.int,
19
+ pd.Int64Dtype(): Dtype.int,
20
+ np.dtype('float32'): Dtype.float,
21
+ pd.Float32Dtype(): Dtype.float,
22
+ np.dtype('float64'): Dtype.float,
23
+ pd.Float64Dtype(): Dtype.float,
24
+ np.dtype('object'): Dtype.string,
25
+ pd.StringDtype(storage='python'): Dtype.string,
26
+ pd.StringDtype(storage='pyarrow'): Dtype.string,
27
+ pa.string(): Dtype.string,
28
+ pa.binary(): Dtype.binary,
29
+ np.dtype('datetime64[ns]'): Dtype.date,
30
+ np.dtype('timedelta64[ns]'): Dtype.timedelta,
31
+ pa.list_(pa.float32()): Dtype.floatlist,
32
+ pa.list_(pa.int64()): Dtype.intlist,
33
+ pa.list_(pa.string()): Dtype.stringlist,
34
+ }
35
+
36
+
37
+ def infer_dtype(ser: pd.Series) -> Dtype:
38
+ """Extracts the :class:`Dtype` from a :class:`pandas.Series`.
39
+
40
+ Args:
41
+ ser: A :class:`pandas.Series` to analyze.
42
+
43
+ Returns:
44
+ The data type.
45
+ """
46
+ if pd.api.types.is_datetime64_any_dtype(ser.dtype):
47
+ return Dtype.date
48
+
49
+ if isinstance(ser.dtype, pd.CategoricalDtype):
50
+ return Dtype.string
51
+
52
+ if pd.api.types.is_object_dtype(ser.dtype):
53
+ index = ser.iloc[:1000].first_valid_index()
54
+ if index is not None and pd.api.types.is_list_like(ser[index]):
55
+ pos = ser.index.get_loc(index)
56
+ assert isinstance(pos, int)
57
+ ser = ser.iloc[pos:pos + 1000].dropna()
58
+
59
+ if not ser.map(pd.api.types.is_list_like).all():
60
+ raise ValueError("Data contains a mix of list-like and "
61
+ "non-list-like values")
62
+
63
+ # Remove all empty Python lists without known data type:
64
+ ser = ser[ser.map(lambda x: not isinstance(x, list) or len(x) > 0)]
65
+
66
+ # Infer unique data types in this series:
67
+ dtypes = ser.apply(lambda x: PANDAS_TO_DTYPE.get(
68
+ np.array(x).dtype, Dtype.string)).unique().tolist()
69
+
70
+ invalid_dtypes = set(dtypes) - {
71
+ Dtype.string,
72
+ Dtype.int,
73
+ Dtype.float,
74
+ }
75
+ if len(invalid_dtypes) > 0:
76
+ raise ValueError(f"Data contains unsupported list data types: "
77
+ f"{list(invalid_dtypes)}")
78
+
79
+ if Dtype.string in dtypes:
80
+ return Dtype.stringlist
81
+
82
+ if dtypes == [Dtype.int]:
83
+ return Dtype.intlist
84
+
85
+ return Dtype.floatlist
86
+
87
+ if ser.dtype not in PANDAS_TO_DTYPE:
88
+ raise ValueError(f"Unsupported data type '{ser.dtype}'")
89
+
90
+ return PANDAS_TO_DTYPE[ser.dtype]