Skip to content

Conversation

@maliktafheem
Copy link

Summary

Fixes #59053

Series.clip() raises TypeError: len() of unsized object when passed 0-dimensional numpy arrays as lower or upper bounds.

Problem

import numpy as np
import pandas as pd

pd.Series([-1, 2, 3]).clip(lower=np.array(0))
# TypeError: len() of unsized object

Root Cause

In Series._flex_method, when other is a numpy array, the code immediately calls len(other) without checking if it's a 0-dimensional array. 0-dimensional arrays have no length and should be treated as scalars.

Solution

Before the length check, detect 0-dimensional numpy arrays and convert them to scalars using .item():

elif isinstance(other, (np.ndarray, list, tuple, ExtensionArray)):
    # Handle 0-dimensional numpy arrays as scalars (GH#59053)
    if isinstance(other, np.ndarray) and other.ndim == 0:
        return op(self, other.item())
    if len(other) != len(self):
        raise ValueError("Lengths must be equal")

Testing

Added test_clip_with_zerodim_ndarray test case covering:

  • clip(lower=np.array(0))
  • clip(upper=np.array(1))
  • clip(lower=np.array(0), upper=np.array(2))

Handle 0-dimensional numpy arrays as scalars in Series._flex_method
to fix TypeError when using np.array(scalar) with clip().

Closes pandas-dev#59053

Signed-off-by: Malik Tafheem <[email protected]>
Signed-off-by: Malik Tafheem <[email protected]>
Copy link
Contributor

@biplavbarua biplavbarua left a comment

Choose a reason for hiding this comment

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

Changes look good!

I verified that Series.clip relies on _clip_with_one_bound, which calls Series.ge/le, eventually hitting _flex_method. Intercepting the 0-d array here and unboxing it with .item() is the correct fix at the root level.

One minor suggestion: Since the current test uses np.array(0) (integer), maybe strictly add a case for np.array(1.5) (float) to ensure type casting behaviors remain consistent?

LGTM.

@maliktafheem
Copy link
Author

Thanks for the review and suggestion @biplavbarua! Added a float 0-d array test case (np.array(0.5), np.array(3.0)) to ensure type casting consistency.

Copy link
Contributor

@biplavbarua biplavbarua left a comment

Choose a reason for hiding this comment

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

Thanks @maliktafheem, the tests in b7f9678 look perfect. Appreciate the quick update! LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: Series.clip does not work with scalar numpy arrays.

2 participants