| 2598 | |
| 2599 | @pytest.mark.pandas |
| 2600 | def test_table_from_pandas_schema(): |
| 2601 | # passed schema is source of truth for the columns |
| 2602 | import pandas as pd |
| 2603 | |
| 2604 | df = pd.DataFrame(OrderedDict([('strs', ['', 'foo', 'bar']), |
| 2605 | ('floats', [4.5, 5, None])])) |
| 2606 | |
| 2607 | # with different but compatible schema |
| 2608 | schema = pa.schema([('strs', pa.utf8()), ('floats', pa.float32())]) |
| 2609 | table = pa.Table.from_pandas(df, schema=schema) |
| 2610 | assert pa.types.is_float32(table.column('floats').type) |
| 2611 | assert table.schema.remove_metadata() == schema |
| 2612 | |
| 2613 | # with different and incompatible schema |
| 2614 | schema = pa.schema([('strs', pa.utf8()), ('floats', pa.timestamp('s'))]) |
| 2615 | with pytest.raises((NotImplementedError, TypeError)): |
| 2616 | pa.Table.from_pandas(df, schema=schema) |
| 2617 | |
| 2618 | # schema has columns not present in data -> error |
| 2619 | schema = pa.schema([('strs', pa.utf8()), ('floats', pa.float64()), |
| 2620 | ('ints', pa.int64())]) |
| 2621 | with pytest.raises(KeyError, match='ints'): |
| 2622 | pa.Table.from_pandas(df, schema=schema) |
| 2623 | |
| 2624 | # data has columns not present in schema -> ignored |
| 2625 | schema = pa.schema([('strs', pa.utf8())]) |
| 2626 | table = pa.Table.from_pandas(df, schema=schema) |
| 2627 | assert table.num_columns == 1 |
| 2628 | assert table.schema.remove_metadata() == schema |
| 2629 | assert table.column_names == ['strs'] |
| 2630 | |
| 2631 | |
| 2632 | @pytest.mark.pandas |