Skip to content

Commit

Permalink
feat: create empty Table without schema (#128)
Browse files Browse the repository at this point in the history
### Summary of Changes

We no longer raise an exception when a user creates an empty `Table`
without specifying a schema. `Table([])` is now allows.

`add_row` and `add_rows` must still be adjusted (#127) to allow adding
rows to such an empty `Table`.

---------

Co-authored-by: lars-reimann <lars-reimann@users.noreply.github.com>
  • Loading branch information
lars-reimann and lars-reimann committed Mar 30, 2023
1 parent 20d21c2 commit ddd3f59
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
13 changes: 4 additions & 9 deletions src/safeds/data/tabular/containers/_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
DuplicateColumnNameError,
IndexOutOfBoundsError,
MissingDataError,
MissingSchemaError,
NonNumericColumnError,
SchemaMismatchError,
UnknownColumnNameError,
Expand Down Expand Up @@ -193,14 +192,10 @@ def from_rows(rows: list[Row]) -> Table:

def __init__(self, data: Iterable, schema: Optional[TableSchema] = None):
self._data: pd.Dataframe = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data)
if schema is None:
if self.count_columns() == 0:
raise MissingSchemaError()
self._schema: TableSchema = TableSchema._from_dataframe(self._data)
else:
self._schema = schema
if self._data.empty:
self._data = pd.DataFrame(columns=self._schema.get_column_names())
self._schema: TableSchema = TableSchema._from_dataframe(self._data) if schema is None else schema

if self._data.empty:
self._data = pd.DataFrame(columns=self._schema.get_column_names())

self._data = self._data.reset_index(drop=True)
self._data.columns = list(range(self.count_columns()))
Expand Down
9 changes: 6 additions & 3 deletions tests/safeds/data/tabular/containers/_table/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@


def test_create_empty_table() -> None:
table = Table(
[], TableSchema({"col1": ColumnType.from_numpy_dtype(np.dtype(float))})
)
table = Table([], TableSchema({"col1": ColumnType.from_numpy_dtype(np.dtype(float))}))
col = table.get_column("col1")
assert col.count() == 0
assert isinstance(col.type, type(ColumnType.from_numpy_dtype(np.dtype(float))))
assert col.name == "col1"


def test_create_empty_table_without_schema() -> None:
table = Table([])
assert table.schema == TableSchema({})

0 comments on commit ddd3f59

Please sign in to comment.