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

fix(python): convert object-dtyped NumPy str/bytes arrays to pl.String/pl.Binary instead of pl.Object #13712

Merged
merged 3 commits into from
Jan 23, 2024

Conversation

Wainberg
Copy link
Contributor

Closes #10710 (which was originally about the conversion to NumPy, but this PR addresses the underlying issue better).

Before:

>>> pl.from_numpy(np.array(['a', 'b'], dtype=object))
shape: (2, 1)
┌──────────┐
│ column_0 │
│ ---      │
│ object   │
╞══════════╡
│ a        │
│ b        │
└──────────┘
>>> pl.from_numpy(np.array([np.nan, b'b'], dtype=object))
shape: (2, 1)
┌──────────┐
│ column_0 │
│ ---      │
│ object   │
╞══════════╡
│ nan      │
│ b'b'     │
└──────────┘

After:

>>> pl.from_numpy(np.array(['a', 'b'], dtype=object))
shape: (2, 1)
┌──────────┐
│ column_0 │
│ ---      │
│ str      │
╞══════════╡
│ a        │
│ b        │
└──────────┘
>>> pl.from_numpy(np.array([np.nan, b'b'], dtype=object))
shape: (2, 1)
┌───────────────┐
│ column_0      │
│ ---           │
│ binary        │
╞═══════════════╡
│ null          │
│ [binary data] │
└───────────────┘

This will lead to errors on mixed-type object arrays where the first element is a string or bytes. I'd originally considered something like:

first_type = type(values[0])
if first_type == str and all(type(v) == str for v in values[1:]):
    return PySeries.new_str
if first_type == bytes and all(type(v) == bytes for v in values[1:]):
    return PySeries.new_binary

but that would be much slower since you'd have to iterate in Python over the entire array. More importantly, it would be inconsistent with the pandas-to-polars conversion, which also just checks the type of the first (non-null) element.

Copy link
Member

@ritchie46 ritchie46 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@ritchie46 ritchie46 merged commit c732f26 into pola-rs:main Jan 23, 2024
11 checks passed
@Wainberg Wainberg deleted the numpy-strings branch January 23, 2024 07:52
r-brink pushed a commit to r-brink/polars that referenced this pull request Jan 24, 2024
…g/pl.Binary instead of pl.Object (pola-rs#13712)

Co-authored-by: Wainberg <m.wainberg@utoronto.ca>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fix Bug fix python Related to Python Polars
Projects
None yet
Development

Successfully merging this pull request may close these issues.

to_numpy() converts pl.Utf8 columns to object, not str
2 participants