Skip to content

Commit 3997eb3

Browse files
committed
implement coercion to namedlist
1 parent e653e70 commit 3997eb3

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/biocframe/frame.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,22 @@ def get_data(self) -> Dict[str, Any]:
500500
"""
501501
return self._data
502502

503+
def to_dict(self) -> Dict[str, Any]:
504+
"""Alias for :py:meth:`~get_data`.
505+
506+
Returns:
507+
Dictionary of columns and their values.
508+
"""
509+
return self.get_data()
510+
511+
def to_NamedList(self) -> ut.NamedList:
512+
"""Convert the ``BiocFrame`` to a :py:class:`~biocutils.NamedList`.
513+
514+
Returns:
515+
A ``NamedList`` containing the columns.
516+
"""
517+
return ut.NamedList([self._data[c] for c in self._column_names], names=self._column_names)
518+
503519
@property
504520
def data(self) -> Dict[str, Any]:
505521
"""Alias for :py:attr:`~get_data`."""
@@ -1127,6 +1143,12 @@ def set_columns(self, columns: Dict[Union[str, int], Any], in_place: bool = Fals
11271143
previous = len(output._column_names)
11281144

11291145
for column, value in columns.items():
1146+
if output.shape == (0, 0):
1147+
output._number_of_rows = ut.get_height(value)
1148+
1149+
if output._row_names is not None and len(output._row_names) == 0 and output._number_of_rows > 0:
1150+
output._row_names = None
1151+
11301152
if ut.get_height(value) != output.shape[0]:
11311153
raise ValueError(
11321154
"Length of `value`, does not match the number of the rows,"

tests/test_coercions.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import pytest
2+
from biocframe import BiocFrame
3+
import biocutils as ut
4+
5+
def test_to_dict():
6+
obj = BiocFrame({"A": [1, 2], "B": [3, 4]})
7+
d = obj.to_dict()
8+
9+
assert isinstance(d, dict)
10+
assert d["A"] == [1, 2]
11+
assert d["B"] == [3, 4]
12+
assert d is obj.get_data()
13+
14+
def test_to_NamedList():
15+
obj = BiocFrame({"A": [1, 2], "B": [3, 4]})
16+
17+
nl = obj.to_NamedList()
18+
assert isinstance(nl, ut.NamedList)
19+
assert len(nl) == 2
20+
assert nl.get_names().as_list() == ["A", "B"]
21+
assert nl[0] == [1, 2]
22+
23+
# Test order
24+
obj = BiocFrame({"B": [3, 4], "A": [1, 2]})
25+
obj = obj.set_column_names(["B", "A"])
26+
27+
obj2 = BiocFrame({}, column_names=[])
28+
obj2["Z"] = [1]
29+
obj2["X"] = [2]
30+
31+
nl2 = obj2.to_NamedList()
32+
assert nl2.get_names().as_list() == ["Z", "X"]
33+
assert nl2[0] == [1]
34+
assert nl2[1] == [2]

0 commit comments

Comments
 (0)