hgrecco / pint-pandas

Pandas support for pint
Other
166 stars 40 forks source link

TypeError: unsupported operand type(s) for /: 'str' and 'str #208

Open nabnaj opened 7 months ago

nabnaj commented 7 months ago

df.ShaftPower / df.ShaftSpeed produced the error in the quantify funnction

        def quantify(self, level=-1):
        df = self._obj
        df_columns = df.columns.to_frame()
        unit_col_name = df_columns.columns[level]
        units = df_columns[unit_col_name]
        df_columns = df_columns.drop(columns=unit_col_name)

        df_new = DataFrame(
            {
                i: PintArray((df.values[:, i]).astype(float), unit)      #   <=  proposed change 
andrewgsavage commented 7 months ago

what versions of pandas and pint-pandas are you using?

brookst commented 1 month ago

I'm also seeing this when running the User Guide.

> pint_pandas.show_versions()
{'numpy': '1.26.4', 'pandas': '2.2.2', 'pint': '0.23', 'pint_pandas': '0.5'}
Full traceback: ``` [25]: df_["ShaftTorque"] = df_.ShaftPower / df_.ShaftSpeed --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[25], line 1 ----> 1 df_["ShaftTorque"] = df_.ShaftPower / df_.ShaftSpeed File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pandas/core/ops/common.py:76, in _unpack_zerodim_and_defer..new_method(self, other) 72 return NotImplemented 74 other = item_from_zerodim(other) ---> 76 return method(self, other) File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pandas/core/arraylike.py:210, in OpsMixin.__truediv__(self, other) 208 @unpack_zerodim_and_defer("__truediv__") 209 def __truediv__(self, other): --> 210 return self._arith_method(other, operator.truediv) File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pandas/core/series.py:6135, in Series._arith_method(self, other, op) 6133 def _arith_method(self, other, op): 6134 self, other = self._align_for_op(other) -> 6135 return base.IndexOpsMixin._arith_method(self, other, op) File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pandas/core/base.py:1382, in IndexOpsMixin._arith_method(self, other, op) 1379 rvalues = np.arange(rvalues.start, rvalues.stop, rvalues.step) 1381 with np.errstate(all="ignore"): -> 1382 result = ops.arithmetic_op(lvalues, rvalues, op) 1384 return self._construct_result(result, name=res_name) File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pandas/core/ops/array_ops.py:273, in arithmetic_op(left, right, op) 260 # NB: We assume that extract_array and ensure_wrapped_if_datetimelike 261 # have already been called on `left` and `right`, 262 # and `maybe_prepare_scalar_for_op` has already been called on `right` 263 # We need to special-case datetime64/timedelta64 dtypes (e.g. because numpy 264 # casts integer dtypes to timedelta64 when operating with timedelta64 - GH#22390) 266 if ( 267 should_extension_dispatch(left, right) 268 or isinstance(right, (Timedelta, BaseOffset, Timestamp)) (...) 271 # Timedelta/Timestamp and other custom scalars are included in the check 272 # because numexpr will fail on it, see GH#31457 --> 273 res_values = op(left, right) 274 else: 275 # TODO we should handle EAs consistently and move this check before the if/else 276 # (https://github.com/pandas-dev/pandas/issues/41165) 277 # error: Argument 2 to "_bool_arith_check" has incompatible type 278 # "Union[ExtensionArray, ndarray[Any, Any]]"; expected "ndarray[Any, Any]" 279 _bool_arith_check(op, left, right) # type: ignore[arg-type] File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pint_pandas/pint_array.py:727, in PintArray._create_method.._binop(self, other) 724 rvalues = convert_values(other) 725 # If the operator is not defined for the underlying objects, 726 # a TypeError should be raised --> 727 res = op(lvalues, rvalues) 729 if op.__name__ == "divmod": 730 return ( 731 cls.from_1darray_quantity(res[0]), 732 cls.from_1darray_quantity(res[1]), 733 ) File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pint/facets/plain/quantity.py:1036, in PlainQuantity.__truediv__(self, other) 1034 if isinstance(self.m, int) or isinstance(getattr(other, "m", None), int): 1035 return self._mul_div(other, self._truedivide_cast_int, operator.truediv) -> 1036 return self._mul_div(other, operator.truediv) File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pint/facets/plain/quantity.py:103, in check_implemented..wrapped(self, *args, **kwargs) 101 elif isinstance(other, list) and other and isinstance(other[0], type(self)): 102 return NotImplemented --> 103 return f(self, *args, **kwargs) File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pint/facets/plain/quantity.py:77, in ireduce_dimensions..wrapped(self, *args, **kwargs) 76 def wrapped(self, *args, **kwargs): ---> 77 result = f(self, *args, **kwargs) 78 try: 79 if result._REGISTRY.autoconvert_to_preferred: File ~/notebooks/.direnv/python-3.10.12/lib/python3.10/site-packages/pint/facets/plain/quantity.py:998, in PlainQuantity._mul_div(self, other, magnitude_op, units_op) 995 elif no_offset_units_other == len(other._units) == 1: 996 other = other.to_root_units() --> 998 magnitude = magnitude_op(new_self._magnitude, other._magnitude) 999 units = units_op(new_self._units, other._units) 1001 return self.__class__(magnitude, units) TypeError: unsupported operand type(s) for /: 'str' and 'str' ```
brookst commented 1 month ago

Ah, so I didn't RTFM and skipped ahead. There's a step that converts the strings into appropriate numeric types.

Maybe the docs could point out that the types must be fixed before continuing? Or put that in a single input so it's less likely to be skipped.

In any case this is user error and can be closed.