{"record":{"id":"e12c6ae25024981f","repo":"pandas-dev/pandas","slug":"cannot-apply-ufunc-ufunc-to-mixed-dataframe-and","errorCode":null,"errorMessage":"Cannot apply ufunc {ufunc} to mixed DataFrame and Series inputs.","messagePattern":"Cannot apply ufunc (.+?) to mixed DataFrame and Series inputs\\.","errorType":"exception","errorClass":"NotImplementedError","httpStatus":null,"severity":"error","filePath":"pandas/core/arraylike.py","lineNumber":336,"sourceCode":"            return NotImplemented\n\n    # align all the inputs.\n    types = tuple(type(x) for x in inputs)\n    alignable = [\n        x for x, t in zip(inputs, types, strict=True) if issubclass(t, NDFrame)\n    ]\n\n    if len(alignable) > 1:\n        # This triggers alignment.\n        # At the moment, there aren't any ufuncs with more than two inputs\n        # so this ends up just being x1.index | x2.index, but we write\n        # it to handle *args.\n        set_types = set(types)\n        if len(set_types) > 1 and {DataFrame, Series}.issubset(set_types):\n            # We currently don't handle ufunc(DataFrame, Series)\n            # well. Previously this raised an internal ValueError. We might\n            # support it someday, so raise a NotImplementedError.\n            raise NotImplementedError(\n                f\"Cannot apply ufunc {ufunc} to mixed DataFrame and Series inputs.\"\n            )\n        axes = self.axes\n        for obj in alignable[1:]:\n            # this relies on the fact that we aren't handling mixed\n            # series / frame ufuncs.\n            for i, (ax1, ax2) in enumerate(zip(axes, obj.axes, strict=True)):\n                axes[i] = ax1.union(ax2)\n\n        reconstruct_axes = dict(zip(self._AXIS_ORDERS, axes, strict=True))\n        inputs = tuple(\n            x.reindex(**reconstruct_axes) if issubclass(t, NDFrame) else x\n            for x, t in zip(inputs, types, strict=True)\n        )\n    else:\n        reconstruct_axes = dict(zip(self._AXIS_ORDERS, self.axes, strict=True))\n\n    if self.ndim == 1:","sourceCodeStart":318,"sourceCodeEnd":354,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arraylike.py#L318-L354","documentation":"Raised by NDFrame.__array_ufunc__ in arraylike.py:336 as a NotImplementedError when a numpy ufunc is called with a mix of DataFrame and Series inputs (e.g. np.add(df, series)). Pandas currently only auto-aligns pairs of the same NDFrame kind; a mixed DataFrame+Series pair would need ambiguous axis alignment that isn't implemented, so it is rejected rather than silently producing a wrong result.","triggerScenarios":"np.add(df, s), np.multiply(s, df), or any numpy ufunc where one positional input is a DataFrame and another is a Series. Hit at arraylike.py:326-338 when len(alignable) > 1 and both DataFrame and Series are present in the input type set.","commonSituations":"Passing a row Series (e.g. df.iloc[0]) to a ufunc expecting a scalar per column; mixing a frame and a derived Series in vectorized math; assuming numpy broadcasts a Series across a DataFrame like it does across a 2-D ndarray.","solutions":["Align types: convert the Series to a DataFrame with matching shape (e.g. s.to_frame().T) or extract a numpy array from one input.","Use pandas arithmetic operators which handle alignment: df + s (with axis=) or df.add(s, axis=...).","Pull the underlying ndarray if alignment isn't needed: np.add(df.values, s.values) (be explicit about shapes)."],"exampleFix":"// before\nnp.add(df, s)  # mixed DataFrame + Series\n// after\ndf.add(s, axis=1)  # pandas operator handles alignment\n// or\nnp.add(df.values, s.values)","handlingStrategy":"type-guard","validationCode":"import pandas as pd\ntypes = {type(x) for x in inputs}\nif pd.DataFrame in types and pd.Series in types:\n    raise NotImplementedError('numpy ufunc cannot mix DataFrame and Series inputs; align types first')","typeGuard":"def ufunc_inputs_homogeneous(inputs) -> bool:\n    import pandas as pd\n    types = {type(x) for x in inputs}\n    return not ({pd.DataFrame, pd.Series} <= types)","tryCatchPattern":"try:\n    np.ufunc(df, series)\nexcept NotImplementedError as e:\n    if 'mixed DataFrame and Series' in str(e):\n        df.add(series, axis=1)  # use pandas op with alignment\n    else:\n        raise","preventionTips":["Use pandas arithmetic operators (df + s, df.add(s, axis=)) instead of np.<ufunc> for mixed frame/series math.","If you must call a numpy ufunc, pass .values from both inputs so shapes are explicit."],"tags":["pandas","numpy","ufunc","dataframe","series","alignment"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}