| 1012 | |
| 1013 | @pytest.mark.numpy |
| 1014 | def test_dictionary_to_numpy(): |
| 1015 | expected = pa.array( |
| 1016 | ["foo", "bar", None, "foo"] |
| 1017 | ).to_numpy(zero_copy_only=False) |
| 1018 | a = pa.DictionaryArray.from_arrays( |
| 1019 | pa.array([0, 1, None, 0]), |
| 1020 | pa.array(['foo', 'bar']) |
| 1021 | ) |
| 1022 | np.testing.assert_array_equal(a.to_numpy(zero_copy_only=False), |
| 1023 | expected) |
| 1024 | |
| 1025 | with pytest.raises(pa.ArrowInvalid): |
| 1026 | # If this would be changed to no longer raise in the future, |
| 1027 | # ensure to test the actual result because, currently, to_numpy takes |
| 1028 | # for granted that when zero_copy_only=True there will be no nulls |
| 1029 | # (it's the decoding of the DictionaryArray that handles the nulls and |
| 1030 | # this is only activated with zero_copy_only=False) |
| 1031 | a.to_numpy(zero_copy_only=True) |
| 1032 | |
| 1033 | anonulls = pa.DictionaryArray.from_arrays( |
| 1034 | pa.array([0, 1, 1, 0]), |
| 1035 | pa.array(['foo', 'bar']) |
| 1036 | ) |
| 1037 | expected = pa.array( |
| 1038 | ["foo", "bar", "bar", "foo"] |
| 1039 | ).to_numpy(zero_copy_only=False) |
| 1040 | np.testing.assert_array_equal(anonulls.to_numpy(zero_copy_only=False), |
| 1041 | expected) |
| 1042 | |
| 1043 | with pytest.raises(pa.ArrowInvalid): |
| 1044 | anonulls.to_numpy(zero_copy_only=True) |
| 1045 | |
| 1046 | afloat = pa.DictionaryArray.from_arrays( |
| 1047 | pa.array([0, 1, 1, 0]), |
| 1048 | pa.array([13.7, 11.0]) |
| 1049 | ) |
| 1050 | expected = pa.array([13.7, 11.0, 11.0, 13.7]).to_numpy() |
| 1051 | np.testing.assert_array_equal(afloat.to_numpy(zero_copy_only=True), |
| 1052 | expected) |
| 1053 | np.testing.assert_array_equal(afloat.to_numpy(zero_copy_only=False), |
| 1054 | expected) |
| 1055 | |
| 1056 | afloat2 = pa.DictionaryArray.from_arrays( |
| 1057 | pa.array([0, 1, None, 0]), |
| 1058 | pa.array([13.7, 11.0]) |
| 1059 | ) |
| 1060 | expected = pa.array( |
| 1061 | [13.7, 11.0, None, 13.7] |
| 1062 | ).to_numpy(zero_copy_only=False) |
| 1063 | np.testing.assert_allclose( |
| 1064 | afloat2.to_numpy(zero_copy_only=False), |
| 1065 | expected, |
| 1066 | equal_nan=True |
| 1067 | ) |
| 1068 | |
| 1069 | # Testing for integers can reveal problems related to dealing |
| 1070 | # with None values, as a numpy array of int dtype |
| 1071 | # can't contain NaN nor None. |