|
4 | 4 | import pytest |
5 | 5 |
|
6 | 6 | from pandas._libs.sparse import IntIndex |
| 7 | +from pandas.compat.numpy import np_version_gt2 |
7 | 8 |
|
8 | 9 | import pandas as pd |
9 | 10 | from pandas import ( |
@@ -480,3 +481,33 @@ def test_zero_sparse_column(): |
480 | 481 |
|
481 | 482 | expected = pd.DataFrame({"A": SparseArray([0, 0]), "B": [1, 3]}, index=[0, 2]) |
482 | 483 | tm.assert_frame_equal(result, expected) |
| 484 | + |
| 485 | + |
| 486 | +def test_array_interface(arr_data, arr): |
| 487 | + # https://github.com/pandas-dev/pandas/pull/60046 |
| 488 | + result = np.asarray(arr) |
| 489 | + tm.assert_numpy_array_equal(result, arr_data) |
| 490 | + |
| 491 | + # it always gives a copy by default |
| 492 | + result_copy1 = np.asarray(arr) |
| 493 | + result_copy2 = np.asarray(arr) |
| 494 | + assert not np.may_share_memory(result_copy1, result_copy2) |
| 495 | + |
| 496 | + # or with explicit copy=True |
| 497 | + result_copy1 = np.array(arr, copy=True) |
| 498 | + result_copy2 = np.array(arr, copy=True) |
| 499 | + assert not np.may_share_memory(result_copy1, result_copy2) |
| 500 | + |
| 501 | + if not np_version_gt2: |
| 502 | + # copy=False semantics are only supported in NumPy>=2. |
| 503 | + return |
| 504 | + |
| 505 | + # for sparse arrays, copy=False is never allowed |
| 506 | + with pytest.raises(ValueError, match="Unable to avoid copy while creating"): |
| 507 | + np.array(arr, copy=False) |
| 508 | + |
| 509 | + # except when there are actually no sparse filled values |
| 510 | + arr2 = SparseArray(np.array([1, 2, 3])) |
| 511 | + result_nocopy1 = np.array(arr2, copy=False) |
| 512 | + result_nocopy2 = np.array(arr2, copy=False) |
| 513 | + assert np.may_share_memory(result_nocopy1, result_nocopy2) |
0 commit comments