Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions leanframe/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,34 @@
import pandas



class DataFrame:
"""A 2D data structure, representing data and deferred computation."""
"""A 2D data structure, representing data and deferred computation.

WARNING: Do not call this constructor directly. Use the factory methods on
Session, instead.
"""

def __init__(self, data):
if isinstance(data, ibis_types.Table):
self._data = data
else:
raise NotImplementedError("DataFrame constructor doesn't support local data yet.")
def __init__(self, data: ibis_types.Table):
self._data = data

@property
def columns(self) -> pandas.Index:
"""The column labels of the DataFrame."""
return pandas.Index(self._data.columns, dtype="object")

def __getitem__(self, key: str):
"""Get a column.

Note: direct row access via an Index is intentionally not implemented by
leanframe. Check out a project like Google's BigQuery DataFrames
(bigframes) if you require indexing.
"""
import leanframe.core.series

# TODO(tswast): Support filtering by a boolean Series if we get a Series
# instead of a key? If so, the Series would have to be a column of the
# current DataFrame, only. No joins by index key are available.
return leanframe.core.series.Series(self._data[key])

def to_pandas(self) -> pandas.DataFrame:
return self._data.to_pandas()
40 changes: 40 additions & 0 deletions leanframe/core/series.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Copyright 2025 Google LLC, LeanFrame Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Series is a one dimensional data structure."""

from __future__ import annotations

import pandas
import ibis.expr.types as ibis_types


class Series:
"""A 1D data structure, representing a column.

WARNING: Do not call this constructor directly. Use the factory methods on
Session, instead.
"""

def __init__(self, data: ibis_types.Column):
self._data = data

@property
def name(self) -> str:
"""Name of the column."""
return self._data.get_name()

def to_pandas(self) -> pandas.Series:
"""Convert to a pandas Series."""
return self._data.to_pandas()
27 changes: 25 additions & 2 deletions leanframe/core/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,19 @@

from __future__ import annotations

import random

import ibis
import ibis.expr.types as ibis_types
import pandas


import leanframe.core.frame
_ALPHABET = "abcdefghijklmnopqrstufwxyz"


class Session:
"""Manages a connection to an ibis backend and emulates the pandas module.

Defaults to BigQuery.
"""

Expand All @@ -35,4 +40,22 @@ def __init__(self, backend: ibis.BaseBackend | None):
self._backend = backend

def read_sql_table(self, table_name: str):
"""Create a DataFrame pointing to the table called ``table_name``."""
import leanframe.core.frame

return leanframe.core.frame.DataFrame(self._backend.table(table_name))

def DataFrame(self, data: ibis_types.Table | pandas.DataFrame):
"""Construct a DataFrame."""
import leanframe.core.frame

if isinstance(data, ibis_types.Table):
return leanframe.core.frame.DataFrame(data)
elif isinstance(data, pandas.DataFrame):
table_name = f"lf_{''.join(random.choices(_ALPHABET, k=10))}"
table = self._backend.create_table(table_name, data, temp=True)
return leanframe.core.frame.DataFrame(table)
else:
raise NotImplementedError(
f"DataFrame constructor doesn't support {type(data)} data yet."
)
6 changes: 0 additions & 6 deletions main.py

This file was deleted.

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ dependencies = [
[dependency-groups]
dev = [
"ibis-framework[duckdb]>=10.6.0",
"ipython>=8.37.0",
"pytest>=8.4.1",
"ruff>=0.12.4",
]

[build-system]
Expand Down
2 changes: 1 addition & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# limitations under the License.
2 changes: 1 addition & 1 deletion tests/unit/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def session() -> leanframe.Session:
"""A Session based on a local engine for unit testing."""
backend = ibis.duckdb.connect()

# Create a few test tables before
# Create a few test tables before
backend.raw_sql(
f"""
CREATE TABLE veggies AS
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/test_frame.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Copyright 2025 Google LLC, LeanFrame Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import pandas

import leanframe
import leanframe.core.series


def test_dataframe_getitem_with_column(session: leanframe.Session):
"""Read a table with simple scalar values."""

df_lf = session.DataFrame(
pandas.DataFrame(
{
"col1": [1, 2, 3],
"col2": ["a", "b", "c"],
}
)
)
series_1 = df_lf["col1"]
assert isinstance(series_1, leanframe.core.series.Series)
assert series_1.name == "col1"
# TODO(tswast): check dtype

series_2 = df_lf["col2"]
assert isinstance(series_2, leanframe.core.series.Series)
assert series_2.name == "col2"
# TODO(tswast): check dtype
48 changes: 48 additions & 0 deletions tests/unit/test_series.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Copyright 2025 Google LLC, LeanFrame Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import pandas
import pandas.testing
import pytest

import leanframe


@pytest.mark.parametrize(
("series_pd",),
(
pytest.param(
pandas.Series([1, 2, 3]),
id="int64",
),
pytest.param(
pandas.Series([1.0, float("nan"), 3.0]),
id="float64",
),
),
)
def test_to_pandas(session: leanframe.Session, series_pd: pandas.Series):
df_pd = pandas.DataFrame(
{
"my_col": series_pd,
}
)
df_lf = session.DataFrame(df_pd)

result = df_lf["my_col"].to_pandas()

# TODO(tswast): Allow input dtype != output dtype with an "expected_dtype" parameter.
pandas.testing.assert_series_equal(result, series_pd, check_names=False)
Loading