Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/pandas/core/interchange/buffer.py: 47%
26 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1from __future__ import annotations
3import numpy as np
5from pandas.core.interchange.dataframe_protocol import (
6 Buffer,
7 DlpackDeviceType,
8)
9from pandas.util.version import Version
11_NUMPY_HAS_DLPACK = Version(np.__version__) >= Version("1.22.0")
14class PandasBuffer(Buffer):
15 """
16 Data in the buffer is guaranteed to be contiguous in memory.
17 """
19 def __init__(self, x: np.ndarray, allow_copy: bool = True) -> None:
20 """
21 Handle only regular columns (= numpy arrays) for now.
22 """
23 if not x.strides == (x.dtype.itemsize,):
24 # The protocol does not support strided buffers, so a copy is
25 # necessary. If that's not allowed, we need to raise an exception.
26 if allow_copy:
27 x = x.copy()
28 else:
29 raise RuntimeError(
30 "Exports cannot be zero-copy in the case "
31 "of a non-contiguous buffer"
32 )
34 # Store the numpy array in which the data resides as a private
35 # attribute, so we can use it to retrieve the public attributes
36 self._x = x
38 @property
39 def bufsize(self) -> int:
40 """
41 Buffer size in bytes.
42 """
43 return self._x.size * self._x.dtype.itemsize
45 @property
46 def ptr(self) -> int:
47 """
48 Pointer to start of the buffer as an integer.
49 """
50 return self._x.__array_interface__["data"][0]
52 def __dlpack__(self):
53 """
54 Represent this structure as DLPack interface.
55 """
56 if _NUMPY_HAS_DLPACK:
57 return self._x.__dlpack__()
58 raise NotImplementedError("__dlpack__")
60 def __dlpack_device__(self) -> tuple[DlpackDeviceType, int | None]:
61 """
62 Device type and device ID for where the data in the buffer resides.
63 """
64 return (DlpackDeviceType.CPU, None)
66 def __repr__(self) -> str:
67 return (
68 "PandasBuffer("
69 + str(
70 {
71 "bufsize": self.bufsize,
72 "ptr": self.ptr,
73 "device": self.__dlpack_device__()[0].name,
74 }
75 )
76 + ")"
77 )