diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 9209536ff13f9..29ab51c582a97 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -1448,6 +1448,7 @@ Conversion - Bug in :meth:`DataFrame.combine_first` in which column types were unexpectedly converted to float (:issue:`20699`) - Bug in :meth:`DataFrame.clip` in which column types are not preserved and casted to float (:issue:`24162`) +- Bug in :meth:`DataFrame.clip` when order of columns of dataframes doesn't match, result observed is wrong in numeric values (:issue:`20911`) Strings ^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a8d5e4aa772cc..eb14a26e75a9c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7176,7 +7176,7 @@ def _clip_with_one_bound(self, threshold, method, axis, inplace): if isinstance(self, ABCSeries): threshold = pd.Series(threshold, index=self.index) else: - threshold = _align_method_FRAME(self, np.asarray(threshold), + threshold = _align_method_FRAME(self, threshold, axis) return self.where(subset, threshold, axis=axis, inplace=inplace) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index baf763d7b1d03..6f68828b94a84 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1971,6 +1971,22 @@ def test_clip_against_frame(self, axis): tm.assert_frame_equal(clipped_df[ub_mask], ub[ub_mask]) tm.assert_frame_equal(clipped_df[mask], df[mask]) + def test_clip_against_unordered_columns(self): + # GH 20911 + df1 = DataFrame(np.random.randn(1000, 4), columns=['A', 'B', 'C', 'D']) + df2 = DataFrame(np.random.randn(1000, 4), columns=['D', 'A', 'B', 'C']) + df3 = DataFrame(df2.values - 1, columns=['B', 'D', 'C', 'A']) + result_upper = df1.clip(lower=0, upper=df2) + expected_upper = df1.clip(lower=0, upper=df2[df1.columns]) + result_lower = df1.clip(lower=df3, upper=3) + expected_lower = df1.clip(lower=df3[df1.columns], upper=3) + result_lower_upper = df1.clip(lower=df3, upper=df2) + expected_lower_upper = df1.clip(lower=df3[df1.columns], + upper=df2[df1.columns]) + tm.assert_frame_equal(result_upper, expected_upper) + tm.assert_frame_equal(result_lower, expected_lower) + tm.assert_frame_equal(result_lower_upper, expected_lower_upper) + def test_clip_with_na_args(self, float_frame): """Should process np.nan argument as None """ # GH 17276