Coverage for qdscreen/tests/compat.py: 55%
11 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-17 11:02 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-17 11:02 +0000
1import numpy as np
2import pandas as pd
5def patch_pandas_if_needed():
6 try:
7 pd.DataFrame.to_numpy
8 except AttributeError:
9 def to_numpy(self, dtype=None, copy=False):
10 """
11 Convert the DataFrame to a NumPy array.
13 .. versionadded:: 0.24.0
15 By default, the dtype of the returned array will be the common NumPy
16 dtype of all types in the DataFrame. For example, if the dtypes are
17 ``float16`` and ``float32``, the results dtype will be ``float32``.
18 This may require copying data and coercing values, which may be
19 expensive.
21 Parameters
22 ----------
23 dtype : str or numpy.dtype, optional
24 The dtype to pass to :meth:`numpy.asarray`
25 copy : bool, default False
26 Whether to ensure that the returned value is a not a view on
27 another array. Note that ``copy=False`` does not *ensure* that
28 ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
29 a copy is made, even if not strictly necessary.
31 Returns
32 -------
33 numpy.ndarray
35 See Also
36 --------
37 Series.to_numpy : Similar method for Series.
39 Examples
40 --------
41 >>> pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_numpy()
42 array([[1, 3],
43 [2, 4]])
45 With heterogenous data, the lowest common type will have to
46 be used.
48 >>> df = pd.DataFrame({"A": [1, 2], "B": [3.0, 4.5]})
49 >>> df.to_numpy()
50 array([[1. , 3. ],
51 [2. , 4.5]])
53 For a mix of numeric and non-numeric types, the output array will
54 have object dtype.
56 >>> df['C'] = pd.date_range('2000', periods=2)
57 >>> df.to_numpy()
58 array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],
59 [2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)
60 """
61 result = np.array(self.values, dtype=dtype, copy=copy)
62 return result
64 pd.DataFrame.to_numpy = to_numpy
66 else:
67 pass