diff --git a/src/biocframe/BiocFrame.py b/src/biocframe/BiocFrame.py index e1ec4f1..859ab48 100644 --- a/src/biocframe/BiocFrame.py +++ b/src/biocframe/BiocFrame.py @@ -1162,7 +1162,7 @@ def columns(self) -> ut.Names: """Alias for :py:attr:`~get_column_names`, provided for compatibility with **pandas**.""" return self.get_column_names() - def to_pandas(self) -> "pandas.DataFrame": + def to_pandas(self): """Convert the ``BiocFrame`` into a :py:class:`~pandas.DataFrame` object. Returns: @@ -1170,15 +1170,18 @@ def to_pandas(self) -> "pandas.DataFrame": """ from pandas import DataFrame - _data_copy = OrderedDict() - for col in self.column_names: - _data_copy[col] = self.column(col) - if isinstance(self.column(col), ut.Factor): - _data_copy[col] = _data_copy[col].to_pandas() + if len(self.column_names) > 0: + _data_copy = OrderedDict() + for col in self.column_names: + _data_copy[col] = self.column(col) + if isinstance(self.column(col), ut.Factor): + _data_copy[col] = _data_copy[col].to_pandas() - return DataFrame( - data=_data_copy, index=self._row_names, columns=self._column_names - ) + return DataFrame( + data=_data_copy, index=self._row_names, columns=self._column_names + ) + else: + return DataFrame(data={}, index=range(self._number_of_rows)) @classmethod def from_pandas(cls, input: "pandas.DataFrame") -> "BiocFrame": diff --git a/tests/test_methods.py b/tests/test_methods.py index e9da191..269f2b0 100644 --- a/tests/test_methods.py +++ b/tests/test_methods.py @@ -565,6 +565,10 @@ def test_export_pandas(): assert len(set(pdf.columns).difference(obj.colnames)) == 0 assert pdf["factor"] is not None + emptyobj = BiocFrame(number_of_rows=100) + pdf = emptyobj.to_pandas() + assert len(pdf) == len(emptyobj) + def test_names_generics(): obj = BiocFrame(