| 1272 | |
| 1273 | @pytest.mark.numpy |
| 1274 | def test_map_from_arrays(): |
| 1275 | offsets_arr = np.array([0, 2, 5, 8], dtype='i4') |
| 1276 | offsets = pa.array(offsets_arr, type='int32') |
| 1277 | pykeys = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h'] |
| 1278 | pyitems = list(range(len(pykeys))) |
| 1279 | pypairs = list(zip(pykeys, pyitems)) |
| 1280 | pyentries = [pypairs[:2], pypairs[2:5], pypairs[5:8]] |
| 1281 | keys = pa.array(pykeys, type='binary') |
| 1282 | items = pa.array(pyitems, type='i4') |
| 1283 | |
| 1284 | result = pa.MapArray.from_arrays(offsets, keys, items) |
| 1285 | expected = pa.array(pyentries, type=pa.map_(pa.binary(), pa.int32())) |
| 1286 | |
| 1287 | assert result.equals(expected) |
| 1288 | |
| 1289 | # With nulls |
| 1290 | offsets = [0, None, 2, 6] |
| 1291 | pykeys = [b'a', b'b', b'c', b'd', b'e', b'f'] |
| 1292 | pyitems = [1, 2, 3, None, 4, 5] |
| 1293 | pypairs = list(zip(pykeys, pyitems)) |
| 1294 | pyentries = [pypairs[:2], None, pypairs[2:]] |
| 1295 | keys = pa.array(pykeys, type='binary') |
| 1296 | items = pa.array(pyitems, type='i4') |
| 1297 | |
| 1298 | result = pa.MapArray.from_arrays(offsets, keys, items) |
| 1299 | expected = pa.array(pyentries, type=pa.map_(pa.binary(), pa.int32())) |
| 1300 | |
| 1301 | assert result.equals(expected) |
| 1302 | |
| 1303 | # pass in the type explicitly |
| 1304 | result = pa.MapArray.from_arrays(offsets, keys, items, pa.map_( |
| 1305 | keys.type, |
| 1306 | items.type |
| 1307 | )) |
| 1308 | assert result.equals(expected) |
| 1309 | |
| 1310 | # pass in invalid types |
| 1311 | with pytest.raises(pa.ArrowTypeError, match='Expected map type, got string'): |
| 1312 | pa.MapArray.from_arrays(offsets, keys, items, pa.string()) |
| 1313 | |
| 1314 | with pytest.raises(pa.ArrowTypeError, match='Mismatching map items type'): |
| 1315 | pa.MapArray.from_arrays(offsets, keys, items, pa.map_( |
| 1316 | keys.type, |
| 1317 | # Larger than the original i4 |
| 1318 | pa.int64() |
| 1319 | )) |
| 1320 | |
| 1321 | # pass in null bitmap with type |
| 1322 | result = pa.MapArray.from_arrays([0, 2, 2, 6], keys, items, pa.map_( |
| 1323 | keys.type, |
| 1324 | items.type), |
| 1325 | mask=pa.array([False, True, False], type=pa.bool_()) |
| 1326 | ) |
| 1327 | assert result.null_count == 1 |
| 1328 | assert result.equals(expected) |
| 1329 | |
| 1330 | # pass in null bitmap without the type |
| 1331 | result = pa.MapArray.from_arrays([0, 2, 2, 6], keys, items, |