|
1 | 1 | import numpy as np
|
2 | 2 | import pytest
|
3 | 3 |
|
| 4 | +from pandas.compat.numpy import np_version_gt2 |
| 5 | + |
4 | 6 | from pandas import (
|
5 | 7 | DataFrame,
|
6 | 8 | Series,
|
|
15 | 17 |
|
16 | 18 | @pytest.mark.parametrize(
|
17 | 19 | "method",
|
18 |
| - [lambda ser: ser.values, lambda ser: np.asarray(ser)], |
19 |
| - ids=["values", "asarray"], |
| 20 | + [ |
| 21 | + lambda ser: ser.values, |
| 22 | + lambda ser: np.asarray(ser), |
| 23 | + lambda ser: np.array(ser, copy=False), |
| 24 | + ], |
| 25 | + ids=["values", "asarray", "array"], |
20 | 26 | )
|
21 | 27 | def test_series_values(using_copy_on_write, method):
|
22 | 28 | ser = Series([1, 2, 3], name="name")
|
@@ -45,8 +51,12 @@ def test_series_values(using_copy_on_write, method):
|
45 | 51 |
|
46 | 52 | @pytest.mark.parametrize(
|
47 | 53 | "method",
|
48 |
| - [lambda df: df.values, lambda df: np.asarray(df)], |
49 |
| - ids=["values", "asarray"], |
| 54 | + [ |
| 55 | + lambda df: df.values, |
| 56 | + lambda df: np.asarray(df), |
| 57 | + lambda ser: np.array(ser, copy=False), |
| 58 | + ], |
| 59 | + ids=["values", "asarray", "array"], |
50 | 60 | )
|
51 | 61 | def test_dataframe_values(using_copy_on_write, using_array_manager, method):
|
52 | 62 | df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
@@ -100,7 +110,7 @@ def test_series_to_numpy(using_copy_on_write):
|
100 | 110 | arr[0] = 0
|
101 | 111 | assert ser.iloc[0] == 0
|
102 | 112 |
|
103 |
| - # specify copy=False gives a writeable array |
| 113 | + # specify copy=True gives a writeable array |
104 | 114 | ser = Series([1, 2, 3], name="name")
|
105 | 115 | arr = ser.to_numpy(copy=True)
|
106 | 116 | assert not np.shares_memory(arr, get_array(ser, "name"))
|
@@ -174,6 +184,23 @@ def test_dataframe_multiple_numpy_dtypes():
|
174 | 184 | assert not np.shares_memory(arr, get_array(df, "a"))
|
175 | 185 | assert arr.flags.writeable is True
|
176 | 186 |
|
| 187 | + if np_version_gt2: |
| 188 | + # copy=False semantics are only supported in NumPy>=2. |
| 189 | + |
| 190 | + with pytest.raises(ValueError, match="Unable to avoid copy while creating"): |
| 191 | + arr = np.array(df, copy=False) |
| 192 | + |
| 193 | + arr = np.array(df, copy=True) |
| 194 | + assert arr.flags.writeable is True |
| 195 | + |
| 196 | + |
| 197 | +def test_dataframe_single_block_copy_true(): |
| 198 | + # the copy=False/None cases are tested above in test_dataframe_values |
| 199 | + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) |
| 200 | + arr = np.array(df, copy=True) |
| 201 | + assert not np.shares_memory(arr, get_array(df, "a")) |
| 202 | + assert arr.flags.writeable is True |
| 203 | + |
177 | 204 |
|
178 | 205 | def test_values_is_ea(using_copy_on_write):
|
179 | 206 | df = DataFrame({"a": date_range("2012-01-01", periods=3)})
|
|
0 commit comments