| 318 | @pytest.mark.nopandas |
| 319 | @pytest.mark.pandas |
| 320 | def test_asarray(): |
| 321 | # ensure this is tested both when pandas is present or not (ARROW-6564) |
| 322 | |
| 323 | arr = pa.array(range(4)) |
| 324 | |
| 325 | # The iterator interface gives back an array of Int64Value's |
| 326 | np_arr = np.asarray([_ for _ in arr]) |
| 327 | assert np_arr.tolist() == [0, 1, 2, 3] |
| 328 | assert np_arr.dtype == np.dtype('O') |
| 329 | assert isinstance(np_arr[0], pa.lib.Int64Value) |
| 330 | |
| 331 | # Calling with the arrow array gives back an array with 'int64' dtype |
| 332 | np_arr = np.asarray(arr) |
| 333 | assert np_arr.tolist() == [0, 1, 2, 3] |
| 334 | assert np_arr.dtype == np.dtype('int64') |
| 335 | |
| 336 | # An optional type can be specified when calling np.asarray |
| 337 | np_arr = np.asarray(arr, dtype='str') |
| 338 | assert np_arr.tolist() == ['0', '1', '2', '3'] |
| 339 | |
| 340 | # If PyArrow array has null values, numpy type will be changed as needed |
| 341 | # to support nulls. |
| 342 | arr = pa.array([0, 1, 2, None]) |
| 343 | assert arr.type == pa.int64() |
| 344 | np_arr = np.asarray(arr) |
| 345 | elements = np_arr.tolist() |
| 346 | assert elements[:3] == [0., 1., 2.] |
| 347 | assert np.isnan(elements[3]) |
| 348 | assert np_arr.dtype == np.dtype('float64') |
| 349 | |
| 350 | # DictionaryType data will be converted to dense numpy array |
| 351 | arr = pa.DictionaryArray.from_arrays( |
| 352 | pa.array([0, 1, 2, 0, 1]), pa.array(['a', 'b', 'c'])) |
| 353 | np_arr = np.asarray(arr) |
| 354 | assert np_arr.dtype == np.dtype('object') |
| 355 | assert np_arr.tolist() == ['a', 'b', 'c', 'a', 'b'] |
| 356 | |
| 357 | |
| 358 | @pytest.mark.parametrize('ty', [ |