Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dataframe conversions #262

Merged
merged 6 commits into from
Sep 23, 2024
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
#### Functionality improvements

* Convert `by` arg `_by` to allow naming columns `by` in `.mutate()`/`.summarize()`
* Convert `.to_pandas()`/`.to_polars()` to `.as_pandas()`/`.as_polars()`

#### New functions

* `as_tibble()`
* `is_tibble()`
* `where()`

## v0.2.19
Expand Down
9 changes: 9 additions & 0 deletions tests/test_tibble.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,3 +463,12 @@ def test_funs_in_a_row():
df.tail()
df.arrange('x', 'y')
assert True, "Functions in a row failed"

def test_conversion():
"""Can convert"""
df = tp.tibble(a = ["a", "a", "a"], b = ["b", "b", "b"], c = range(3))
actual = df.as_polars()
expected = pl.DataFrame(dict(a = ["a", "a", "a"], b = ["b", "b", "b"], c = range(3)))
assert actual.equals(expected), "as_polars failed"
assert tp.is_tibble(df) == True, "is_tibble failed"
assert tp.as_tibble(actual).equals(df), "as_tibble failed"
39 changes: 39 additions & 0 deletions tidypolars/tibble_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from operator import not_

__all__ = [
"as_tibble",
"is_tibble",
"tibble",
"desc",
"from_pandas", "from_polars"
Expand Down Expand Up @@ -959,6 +961,43 @@ def desc(x):
class DescCol(pl.Expr):
pass

def as_tibble(x):
"""
Convert an object to a tibble

Parameters
----------
x : [pl.DataFrame, pd.DataFrame, dict]
Object to convert to a tibble

Examples
--------
>>> tp.as_tibble(polars_df)
"""
if isinstance(x, pl.DataFrame):
out = from_polars(x)
elif isinstance(x, dict):
out = tibble(x)
elif is_tibble(x):
out = x
else:
out = pl.from_dataframe(x)
return out

def is_tibble(x):
"""
Is an object to a tibble

Parameters
----------
x : object

Examples
--------
>>> tp.is_tibble(df)
"""
return isinstance(x, tibble)

def from_polars(df):
"""
Convert from polars DataFrame to tibble
Expand Down
Loading