jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_first():
    i = pd.date_range("2010-04-09", periods=400, freq="2D")
    modin_df = pd.DataFrame({"A": list(range(400)), "B": list(range(400))}, index=i)
    pandas_df = pandas.DataFrame(
        {"A": list(range(400)), "B": list(range(400))}, index=i
    )
    with pytest.warns(FutureWarning, match="first is deprecated and will be removed"):
        modin_result = modin_df.loc[:modin_df.index[2]]
    df_equals(modin_result, pandas_df.loc[:pandas_df.index[2]])
    df_equals(modin_df.loc[:modin_df.index[19]], pandas_df.loc[:pandas_df.index[19]])
//  [python]
def test_groupby_level_no_obs(self):
        # #1697
        midx = MultiIndex.from_tuples([('f1', 's1'), ('f1', 's2'),
                                       ('f2', 's1'), ('f2', 's2'),
                                       ('f3', 's1'), ('f3', 's2')])
        df = DataFrame(
            [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx)
        df1 = df.select(lambda u: u[0] in ['f2', 'f3'], axis=1)

        grouped = df1.groupby(axis=1, level=0)
        result = grouped.sum()
        self.assertTrue((result.columns == ['f2', 'f3']).all())
//  [python]
def test_groupby_level_no_obs(self):
        # #1697
        midx = MultiIndex.from_tuples([('f1', 's1'), ('f1', 's2'),
                                       ('f2', 's1'), ('f2', 's2'),
                                       ('f3', 's1'), ('f3', 's2')])
        df = DataFrame(
            [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx)
        df1 = df.loc[:, df.columns.get_level_values(0).isin(['f2', 'f3'])]

        grouped = df1.groupby(axis=1, level=0)
        result = grouped.sum()
        self.assertTrue((result.columns == ['f2', 'f3']).all())
//  [python]
def test_last():
    modin_index = pd.date_range("2010-04-09", periods=400, freq="2D")
    pandas_index = pandas.date_range("2010-04-09", periods=400, freq="2D")
    modin_df = pd.DataFrame(
        {"A": list(range(400)), "B": list(range(400))}, index=modin_index
    )
    pandas_df = pandas.DataFrame(
        {"A": list(range(400)), "B": list(range(400))}, index=pandas_index
    )
    with pytest.warns(FutureWarning, match="last is deprecated and will be removed"):
        modin_result = modin_df.last("3D")
    df_equals(modin_result, pandas_df.last("3D"))
    df_equals(modin_df.last("20D"), pandas_df.last("20D"))
//  [python]
def test_last():
    modin_index = pd.date_range("2010-04-09", periods=400, freq="2D")
    pandas_index = pandas.date_range("2010-04-09", periods=400, freq="2D")
    modin_df = pd.DataFrame(
        {"A": list(range(400)), "B": list(range(400))}, index=modin_index
    )
    pandas_df = pandas.DataFrame(
        {"A": list(range(400)), "B": list(range(400))}, index=pandas_index
    )
    with pytest.warns(FutureWarning, match="last is deprecated and will be removed"):
        modin_result = modin_df.loc[modin_df.index[-1] - pd.Timedelta("3D"):]
    df_equals(modin_result, pandas_df.loc[pandas_df.index[-1] - pd.Timedelta("3D"):])
    df_equals(modin_df.loc[modin_df.index[-1] - pd.Timedelta("20D"):], pandas_df.loc[pandas_df.index[-1] - pd.Timedelta("20D"):])
//  [python]
def test_last(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        psdf = ps.from_pandas(pdf)
        self.assert_eq(pdf.last("1D"), psdf.last("1D"))
        self.assert_eq(pdf.last(DateOffset(days=1)), psdf.last(DateOffset(days=1)))
        with self.assertRaisesRegex(TypeError, "'last' only supports a DatetimeIndex"):
            ps.DataFrame([1, 2, 3, 4]).last("1D")
//  [python]
def test_last(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        psdf = ps.from_pandas(pdf)
        self.assert_eq(pdf.loc[pdf.index[-1:]], psdf.loc[psdf.index[-1:]])
        self.assert_eq(pdf.loc[pdf.index[-1:]], psdf.loc[psdf.index[-1:]])
        with self.assertRaisesRegex(TypeError, "'last' only supports a DatetimeIndex"):
            ps.DataFrame([1, 2, 3, 4]).last("1D")
//  [python]
def test_first(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        psdf = ps.from_pandas(pdf)
        self.assert_eq(pdf.first("1D"), psdf.first("1D"))
        self.assert_eq(pdf.first(DateOffset(days=1)), psdf.first(DateOffset(days=1)))
        with self.assertRaisesRegex(TypeError, "'first' only supports a DatetimeIndex"):
            ps.DataFrame([1, 2, 3, 4]).first("1D")
//  [python]
def test_first(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        psdf = ps.from_pandas(pdf)
        self.assert_eq(pdf.loc[:pdf.index[0] + pd.Timedelta("1D")], psdf.loc[:psdf.index[0] + pd.Timedelta("1D")])
        self.assert_eq(pdf.loc[:pdf.index[0] + DateOffset(days=1)], psdf.loc[:psdf.index[0] + DateOffset(days=1)])
        with self.assertRaisesRegex(TypeError, "'first' only supports a DatetimeIndex"):
            ps.DataFrame([1, 2, 3, 4]).first("1D")
//  [python]
def test_last(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        kdf = ks.from_pandas(pdf)
        self.assert_eq(pdf.last("1D"), kdf.last("1D"))
        self.assert_eq(pdf.last(DateOffset(days=1)), kdf.last(DateOffset(days=1)))
        with self.assertRaisesRegex(TypeError, "'last' only supports a DatetimeIndex"):
            ks.DataFrame([1, 2, 3, 4]).last("1D")
//  [python]
def test_last(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        kdf = ks.from_pandas(pdf)
        self.assert_eq(pdf.loc[pdf.index[-1:]], kdf.last("1D"))
        self.assert_eq(pdf.loc[pdf.index[-1:]], kdf.last(DateOffset(days=1)))
        with self.assertRaisesRegex(TypeError, "'last' only supports a DatetimeIndex"):
            ks.DataFrame([1, 2, 3, 4]).last("1D")
//  [python]
def test_first(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        kdf = ks.from_pandas(pdf)
        self.assert_eq(pdf.first("1D"), kdf.first("1D"))
        self.assert_eq(pdf.first(DateOffset(days=1)), kdf.first(DateOffset(days=1)))
        with self.assertRaisesRegex(TypeError, "'first' only supports a DatetimeIndex"):
            ks.DataFrame([1, 2, 3, 4]).first("1D")
//  [python]
def test_first(self):
        index = pd.date_range("2018-04-09", periods=4, freq="2D")
        pdf = pd.DataFrame([1, 2, 3, 4], index=index)
        kdf = ks.from_pandas(pdf)
        self.assert_eq(pdf.loc[:pdf.index[0] + pd.Timedelta("1D")], kdf.first("1D"))
        self.assert_eq(pdf.loc[:pdf.index[0] + DateOffset(days=1)], kdf.first(DateOffset(days=1)))
        with self.assertRaisesRegex(TypeError, "'first' only supports a DatetimeIndex"):
            ks.DataFrame([1, 2, 3, 4]).first("1D")
//  [python]
def test_unsortedindex(self):
        # GH 11897
        mi = pd.MultiIndex.from_tuples([('z', 'a'), ('x', 'a'), ('y', 'b'),
                                        ('x', 'b'), ('y', 'a'), ('z', 'b')],
                                       names=['one', 'two'])
        df = pd.DataFrame([[i, 10 * i] for i in lrange(6)], index=mi,
                          columns=['one', 'two'])

        # GH 16734: not sorted, but no real slicing
        result = df.ix['z', 'a']
        expected = df.iloc[0]
        tm.assert_series_equal(result, expected)

        with pytest.raises(UnsortedIndexError):
            df.ix['z', slice('a')]
        df.sort_index(inplace=True)
        assert len(df.ix['z', :]) == 2

        with pytest.raises(KeyError):
            df.ix['q', :]
//  [python]
def test_unsortedindex(self):
        # GH 11897
        mi = pd.MultiIndex.from_tuples([('z', 'a'), ('x', 'a'), ('y', 'b'),
                                        ('x', 'b'), ('y', 'a'), ('z', 'b')],
                                       names=['one', 'two'])
        df = pd.DataFrame([[i, 10 * i] for i in lrange(6)], index=mi,
                          columns=['one', 'two'])

        # GH 16734: not sorted, but no real slicing
        result = df.loc(axis=0)['z', 'a']
        expected = df.iloc[0]
        tm.assert_series_equal(result, expected)

        with pytest.raises(UnsortedIndexError):
            df.loc(axis=0)['z', slice('a')]
        df.sort_index(inplace=True)
        assert len(df.loc(axis=0)['z', :]) == 2

        with pytest.raises(KeyError):
            df.loc(axis=0)['q', :]
//  [python]
def test_loc_axis_1_slice():
    # GH 10586
    cols = [(yr, m) for yr in [2014, 2015] for m in [7, 8, 9, 10]]
    df = DataFrame(
        np.ones((10, 8)),
        index=tuple("ABCDEFGHIJ"),
        columns=MultiIndex.from_tuples(cols),
    )
    result = df.loc[(2014, 9):(2015, 8),:]
    expected = DataFrame(
        np.ones((10, 4)),
        index=tuple("ABCDEFGHIJ"),
        columns=MultiIndex.from_tuples([(2014, 9), (2014, 10), (2015, 7), (2015, 8)]),
    )
    tm.assert_frame_equal(result, expected)
//  [python]
def test_loc_axis_1_slice():
    # GH 10586
    cols = [(yr, m) for yr in [2014, 2015] for m in [7, 8, 9, 10]]
    df = DataFrame(
        np.ones((10, 8)),
        index=tuple("ABCDEFGHIJ"),
        columns=MultiIndex.from_tuples(cols),
    )
    result = df.loc(axis=1)[(2014, 9):(2015, 8)]
    expected = DataFrame(
        np.ones((10, 4)),
        index=tuple("ABCDEFGHIJ"),
        columns=MultiIndex.from_tuples([(2014, 9), (2014, 10), (2015, 7), (2015, 8)]),
    )
    tm.assert_frame_equal(result, expected)
//  [python]
def test_unsortedindex(self):
        # GH 11897
        mi = pd.MultiIndex.from_tuples([('z', 'a'), ('x', 'a'), ('y', 'b'),
                                        ('x', 'b'), ('y', 'a'), ('z', 'b')],
                                       names=['one', 'two'])
        df = pd.DataFrame([[i, 10 * i] for i in lrange(6)], index=mi,
                          columns=['one', 'two'])

        with pytest.raises(UnsortedIndexError):
            df.ix['z', :]
        df.sort_index(inplace=True)
        assert len(df.ix['z', :]) == 2

        with pytest.raises(KeyError):
            df.ix['q', :]
//  [python]
def test_unsortedindex(self):
        # GH 11897
        mi = pd.MultiIndex.from_tuples([('z', 'a'), ('x', 'a'), ('y', 'b'),
                                        ('x', 'b'), ('y', 'a'), ('z', 'b')],
                                       names=['one', 'two'])
        df = pd.DataFrame([[i, 10 * i] for i in lrange(6)], index=mi,
                          columns=['one', 'two'])

        with pytest.raises(UnsortedIndexError):
            df.loc(axis=0)['z', :]
        df.sort_index(inplace=True)
        assert len(df.loc(axis=0)['z', :]) == 2

        with pytest.raises(KeyError):
            df.loc(axis=0)['q', :]
//  [python]
def test_select(self):

        # deprecated: gh-12410
        f = lambda x: x.weekday() == 2
        index = self.tsframe.index[[f(x) for x in self.tsframe.index]]
        expected_weekdays = self.tsframe.reindex(index=index)

        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            result = self.tsframe.select(f, axis=0)
            assert_frame_equal(result, expected_weekdays)

            result = self.frame.select(lambda x: x in ('B', 'D'), axis=1)
            expected = self.frame.reindex(columns=['B', 'D'])
            assert_frame_equal(result, expected, check_names=False)

        # replacement
        f = lambda x: x.weekday == 2
        result = self.tsframe.loc(axis=0)[f(self.tsframe.index)]
        assert_frame_equal(result, expected_weekdays)

        crit = lambda x: x in ['B', 'D']
        result = self.frame.loc(axis=1)[(self.frame.columns.map(crit))]
        expected = self.frame.reindex(columns=['B', 'D'])
        assert_frame_equal(result, expected, check_names=False)

        # doc example
        df = DataFrame({'A': [1, 2, 3]}, index=['foo', 'bar', 'baz'])

        crit = lambda x: x in ['bar', 'baz']
        with tm.assert_produces_warning(FutureWarning):
            expected = df.select(crit)
        result = df.loc[df.index.map(crit)]
        assert_frame_equal(result, expected, check_names=False)
//  [python]
def test_select(self):

        # deprecated: gh-12410
        f = lambda x: x.weekday() == 2
        index = self.tsframe.index[[f(x) for x in self.tsframe.index]]
        expected_weekdays = self.tsframe.reindex(index=index)

        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            result = self.tsframe.loc[lambda x: x.weekday() == 2]
            assert_frame_equal(result, expected_weekdays)

            result = self.frame.loc[:, lambda x: x.isin(['B', 'D'])]
            expected = self.frame.reindex(columns=['B', 'D'])
            assert_frame_equal(result, expected, check_names=False)

        # replacement
        f = lambda x: x.weekday == 2
        result = self.tsframe.loc[f(self.tsframe.index)]
        assert_frame_equal(result, expected_weekdays)

        crit = lambda x: x in ['B', 'D']
        result = self.frame.loc[:, (self.frame.columns.map(crit))]
        expected = self.frame.reindex(columns=['B', 'D'])
        assert_frame_equal(result, expected, check_names=False)

        # doc example
        df = DataFrame({'A': [1, 2, 3]}, index=['foo', 'bar', 'baz'])

        crit = lambda x: x in ['bar', 'baz']
        with tm.assert_produces_warning(FutureWarning):
            expected = df.loc[df.index.map(crit)]
        result = df.loc[df.index.map(crit)]
        assert_frame_equal(result, expected, check_names=False)
//  [python]
def test_loc_axis_1_slice():
    # GH 10586
    cols = [(yr, m) for yr in [2014, 2015] for m in [7, 8, 9, 10]]
    df = DataFrame(
        np.ones((10, 8)),
        index=tuple("ABCDEFGHIJ"),
        columns=pd.MultiIndex.from_tuples(cols),
    )
    result = df.loc[(2014, 9):(2015, 8),:]
    expected = DataFrame(
        np.ones((10, 4)),
        index=tuple("ABCDEFGHIJ"),
        columns=pd.MultiIndex.from_tuples(
            [(2014, 9), (2014, 10), (2015, 7), (2015, 8)]
        ),
    )
    tm.assert_frame_equal(result, expected)
//  [python]
def test_loc_axis_1_slice():
    # GH 10586
    cols = [(yr, m) for yr in [2014, 2015] for m in [7, 8, 9, 10]]
    df = DataFrame(
        np.ones((10, 8)),
        index=tuple("ABCDEFGHIJ"),
        columns=pd.MultiIndex.from_tuples(cols),
    )
    result = df.loc(axis=1)[(2014, 9):(2015, 8)]
    expected = DataFrame(
        np.ones((10, 4)),
        index=tuple("ABCDEFGHIJ"),
        columns=pd.MultiIndex.from_tuples(
            [(2014, 9), (2014, 10), (2015, 7), (2015, 8)]
        ),
    )
    tm.assert_frame_equal(result, expected)
//  [python]
def test_groupby_level_no_obs(self):
        # #1697
        midx = MultiIndex.from_tuples([('f1', 's1'), ('f1', 's2'), (
            'f2', 's1'), ('f2', 's2'), ('f3', 's1'), ('f3', 's2')])
        df = DataFrame(
            [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx)
        df1 = df.ix[:, df.columns.map(
            lambda u: u[0] in ['f2', 'f3'])]

        grouped = df1.groupby(axis=1, level=0)
        result = grouped.sum()
        assert (result.columns == ['f2', 'f3']).all()
//  [python]
def test_groupby_level_no_obs(self):
        # #1697
        midx = MultiIndex.from_tuples([('f1', 's1'), ('f1', 's2'), (
            'f2', 's1'), ('f2', 's2'), ('f3', 's1'), ('f3', 's2')])
        df = DataFrame(
            [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx)
        df1 = df.loc(axis=1)[df.columns.map(
            lambda u: u[0] in ['f2', 'f3'])]

        grouped = df1.groupby(axis=1, level=0)
        result = grouped.sum()
        assert (result.columns == ['f2', 'f3']).all()
//  [python]
def test_multiindex_setitem_axis_set(self):
        # GH#58116
        dates = pd.date_range("2001-01-01", freq="D", periods=2)
        ids = ["i1", "i2", "i3"]
        index = MultiIndex.from_product([dates, ids], names=["date", "identifier"])
        df = DataFrame(0.0, index=index, columns=["A", "B"])
        df[("2001-01-01", ["i1", "i3"])] = None

        expected = DataFrame(
            [
                [None, None],
                [0.0, 0.0],
                [None, None],
                [0.0, 0.0],
                [0.0, 0.0],
                [0.0, 0.0],
            ],
            index=index,
            columns=["A", "B"],
        )

        tm.assert_frame_equal(df, expected)
//  [python]
def test_multiindex_setitem_axis_set(self):
        # GH#58116
        dates = pd.date_range("2001-01-01", freq="D", periods=2)
        ids = ["i1", "i2", "i3"]
        index = MultiIndex.from_product([dates, ids], names=["date", "identifier"])
        df = DataFrame(0.0, index=index, columns=["A", "B"])
        df.loc(axis=0)["2001-01-01", ["i1", "i3"]] = None

        expected = DataFrame(
            [
                [None, None],
                [0.0, 0.0],
                [None, None],
                [0.0, 0.0],
                [0.0, 0.0],
                [0.0, 0.0],
            ],
            index=index,
            columns=["A", "B"],
        )

        tm.assert_frame_equal(df, expected)
//  [python]
def test_frame_apply_dont_convert_datetime64(self):
        from pandas.tseries.offsets import BDay
        df = DataFrame({'x1': [datetime(1996, 1, 1)]})

        df = df.applymap(lambda x: x + BDay())
        df = df.applymap(lambda x: x + BDay())

        self.assertTrue(df.x1.dtype == 'M8[ns]')
//  [python]
def test_frame_apply_dont_convert_datetime64(self):
        from pandas.tseries.offsets import BDay
        df = DataFrame({'x1': [datetime(1996, 1, 1)]})

        df = df.map(lambda x: x + BDay())
        df = df.map(lambda x: x + BDay())

        self.assertTrue(df.x1.dtype == 'M8[ns]')
//  [python]
def test_groupby_level_no_obs(self):
        # #1697
        midx = MultiIndex.from_tuples(
            [
                ("f1", "s1"),
                ("f1", "s2"),
                ("f2", "s1"),
                ("f2", "s2"),
                ("f3", "s1"),
                ("f3", "s2"),
            ]
        )
        df = DataFrame([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx)
        df1 = df.ix[:, df.columns.map(lambda u: u[0] in ["f2", "f3"])]

        grouped = df1.groupby(axis=1, level=0)
        result = grouped.sum()
        assert (result.columns == ["f2", "f3"]).all()
//  [python]
def test_groupby_level_no_obs(self):
        # #1697
        midx = MultiIndex.from_tuples(
            [
                ("f1", "s1"),
                ("f1", "s2"),
                ("f2", "s1"),
                ("f2", "s2"),
                ("f3", "s1"),
                ("f3", "s2"),
            ]
        )
        df = DataFrame([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx)
        df1 = df.loc(axis=1)[df.columns.map(lambda u: u[0] in ["f2", "f3"])]

        grouped = df1.groupby(axis=1, level=0)
        result = grouped.sum()
        assert (result.columns == ["f2", "f3"]).all()
//  [python]
def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self):
        # see gh-21947
        df = pd.DataFrame(columns=["a"])
        cond = df.applymap(lambda x: x > 0)

        result = df.where(cond)
        tm.assert_frame_equal(result, df)
//  [python]
def test_where_empty_df_and_empty_cond_having_non_bool_dtypes(self):
        # see gh-21947
        df = pd.DataFrame(columns=["a"])
        cond = df.map(lambda x: x > 0)

        result = df.where(cond)
        tm.assert_frame_equal(result, df)
//  [python]
def test_datetime_time(self):
        # test support for datetime.time, GH #8341
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql('test_time', self.conn, index=False)
        res = read_sql_query('SELECT * FROM test_time', self.conn)
        if self.flavor == 'sqlite':
            # comes back as strings
            expected = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(res, expected)
//  [python]
def test_datetime_time(self):
        # test support for datetime.time, GH #8341
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql('test_time', self.conn, index=False)
        res = read_sql_query('SELECT * FROM test_time', self.conn)
        if self.flavor == 'sqlite':
            # comes back as strings
            expected = df.map(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(res, expected)
//  [python]
def test_applymap_na_action(self):
    # Replicates a doctest for na_action which is incompatible with
    # doctest framework
    df = pd.DataFrame([[pd.NA, 2.12], [3.356, 4.567]])
    self._run_test(
        lambda df: df.applymap(lambda x: len(str(x)), na_action='ignore'),
        df,
        # TODO: generate proxy using naive type inference on fn
        check_proxy=False)
//  [python]
def test_applymap_na_action(self):
    # Replicates a doctest for na_action which is incompatible with
    # doctest framework
    df = pd.DataFrame([[pd.NA, 2.12], [3.356, 4.567]])
    self._run_test(
        lambda df: df.map(lambda x: len(str(x)), na_action='ignore'),
        df,
        # TODO: generate proxy using naive type inference on fn
        check_proxy=False)
//  [python]
def test_applymap_float_object_conversion(val):
    # GH 2909: object conversion to float in constructor?
    df = DataFrame(data=[val, "a"])
    result = df.applymap(lambda x: x).dtypes[0]
    assert result == object
//  [python]
def test_applymap_float_object_conversion(val):
    # GH 2909: object conversion to float in constructor?
    df = DataFrame(data=[val, "a"])
    result = df.map(lambda x: x).dtypes[0]
    assert result == object
//  [python]
def test_applymap_numeric(request, data, testfunc):
    modin_df = pd.DataFrame(data)
    pandas_df = pandas.DataFrame(data)

    if name_contains(request.node.name, numeric_dfs):
        try:
            pandas_result = pandas_df.applymap(testfunc)
        except Exception as err:
            with pytest.raises(type(err)):
                modin_df.applymap(testfunc)
        else:
            modin_result = modin_df.applymap(testfunc)
            df_equals(modin_result, pandas_result)
//  [python]
def test_applymap_numeric(request, data, testfunc):
    modin_df = pd.DataFrame(data)
    pandas_df = pandas.DataFrame(data)

    if name_contains(request.node.name, numeric_dfs):
        try:
            pandas_result = pandas_df.map(testfunc)
        except Exception as err:
            with pytest.raises(type(err)):
                modin_df.map(testfunc)
        else:
            modin_result = modin_df.map(testfunc)
            df_equals(modin_result, pandas_result)
//  [python]
def test_applymap_datetimelike(col, val):
    # datetime/timedelta
    df = DataFrame(np.random.random((3, 4)))
    df[col] = val
    result = df.applymap(str)
    assert result.loc[0, col] == str(df.loc[0, col])
//  [python]
def test_applymap_datetimelike(col, val):
    # datetime/timedelta
    df = DataFrame(np.random.random((3, 4)))
    df[col] = val
    result = df.map(str)
    assert result.loc[0, col] == str(df.loc[0, col])
//  [python]
def test_applymap_str():
    # GH 2786
    df = DataFrame(np.random.random((3, 4)))
    df2 = df.copy()
    cols = ["a", "a", "a", "a"]
    df.columns = cols

    expected = df2.applymap(str)
    expected.columns = cols
    result = df.applymap(str)
    tm.assert_frame_equal(result, expected)
//  [python]
def test_applymap_str():
    # GH 2786
    df = DataFrame(np.random.random((3, 4)))
    df2 = df.copy()
    cols = ["a", "a", "a", "a"]
    df.columns = cols

    expected = df2.map(str)
    expected.columns = cols
    result = df.map(str)
    tm.assert_frame_equal(result, expected)
//  [python]
def test_datetime_time(self):
        # test support for datetime.time
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql('test_time', self.conn, index=False)
        res = read_sql_table('test_time', self.conn)
        tm.assert_frame_equal(res, df)

        # GH8341
        # first, use the fallback to have the sqlite adapter put in place
        sqlite_conn = TestSQLiteFallback.connect()
        sql.to_sql(df, "test_time2", sqlite_conn, index=False)
        res = sql.read_sql_query("SELECT * FROM test_time2", sqlite_conn)
        ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
        tm.assert_frame_equal(ref, res)  # check if adapter is in place
        # then test if sqlalchemy is unaffected by the sqlite adapter
        sql.to_sql(df, "test_time3", self.conn, index=False)
        if self.flavor == 'sqlite':
            res = sql.read_sql_query("SELECT * FROM test_time3", self.conn)
            ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(ref, res)
        res = sql.read_sql_table("test_time3", self.conn)
        tm.assert_frame_equal(df, res)
//  [python]
def test_datetime_time(self):
        # test support for datetime.time
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql('test_time', self.conn, index=False)
        res = read_sql_table('test_time', self.conn)
        tm.assert_frame_equal(res, df)

        # GH8341
        # first, use the fallback to have the sqlite adapter put in place
        sqlite_conn = TestSQLiteFallback.connect()
        sql.to_sql(df, "test_time2", sqlite_conn, index=False)
        res = sql.read_sql_query("SELECT * FROM test_time2", sqlite_conn)
        ref = df.map(lambda _: _.strftime("%H:%M:%S.%f"))
        tm.assert_frame_equal(ref, res)  # check if adapter is in place
        # then test if sqlalchemy is unaffected by the sqlite adapter
        sql.to_sql(df, "test_time3", self.conn, index=False)
        if self.flavor == 'sqlite':
            res = sql.read_sql_query("SELECT * FROM test_time3", self.conn)
            ref = df.map(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(ref, res)
        res = sql.read_sql_table("test_time3", self.conn)
        tm.assert_frame_equal(df, res)
//  [python]
def test_applymap(self):
        applied = self.frame.applymap(lambda x: x * 2)
        assert_frame_equal(applied, self.frame * 2)
        result = self.frame.applymap(type)

        # GH #465, function returning tuples
        result = self.frame.applymap(lambda x: (x, x))
        tm.assert_isinstance(result['A'][0], tuple)

        # GH 2909, object conversion to float in constructor?
        df = DataFrame(data=[1,'a'])
        result = df.applymap(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        df = DataFrame(data=[1.,'a'])
        result = df.applymap(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        # GH2786
        df  = DataFrame(np.random.random((3,4)))
        df2 = df.copy()
        cols = ['a','a','a','a']
        df.columns = cols

        expected = df2.applymap(str)
        expected.columns = cols
        result = df.applymap(str)
        assert_frame_equal(result,expected)

        # datetime/timedelta
        df['datetime'] = Timestamp('20130101')
        df['timedelta'] = Timedelta('1 min')
        result = df.applymap(str)
        for f in ['datetime','timedelta']:
            self.assertEquals(result.loc[0,f],str(df.loc[0,f]))
//  [python]
def test_applymap(self):
        applied = self.frame.map(lambda x: x * 2)
        assert_frame_equal(applied, self.frame * 2)
        result = self.frame.map(type)

        # GH #465, function returning tuples
        result = self.frame.map(lambda x: (x, x))
        tm.assert_isinstance(result['A'][0], tuple)

        # GH 2909, object conversion to float in constructor?
        df = DataFrame(data=[1,'a'])
        result = df.map(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        df = DataFrame(data=[1.,'a'])
        result = df.map(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        # GH2786
        df  = DataFrame(np.random.random((3,4)))
        df2 = df.copy()
        cols = ['a','a','a','a']
        df.columns = cols

        expected = df2.map(str)
        expected.columns = cols
        result = df.map(str)
        assert_frame_equal(result,expected)

        # datetime/timedelta
        df['datetime'] = Timestamp('20130101')
        df['timedelta'] = Timedelta('1 min')
        result = df.map(str)
        for f in ['datetime','timedelta']:
            self.assertEquals(result.loc[0,f],str(df.loc[0,f]))
//  [python]
def test_frame_apply_dont_convert_datetime64():
    from pandas.tseries.offsets import BDay

    df = DataFrame({"x1": [datetime(1996, 1, 1)]})

    df = df.applymap(lambda x: x + BDay())
    df = df.applymap(lambda x: x + BDay())

    result = df.x1.dtype
    assert result == "M8[ns]"
//  [python]
def test_frame_apply_dont_convert_datetime64():
    from pandas.tseries.offsets import BDay

    df = DataFrame({"x1": [datetime(1996, 1, 1)]})

    df = df.map(lambda x: x + BDay())
    df = df.map(lambda x: x + BDay())

    result = df.x1.dtype
    assert result == "M8[ns]"
//  [python]
def test_applymap_function_runs_once():
    df = DataFrame({"a": [1, 2, 3]})
    values = []  # Save values function is applied to

    def reducing_function(val):
        values.append(val)

    def non_reducing_function(val):
        values.append(val)
        return val

    for func in [reducing_function, non_reducing_function]:
        del values[:]

        df.applymap(func)
        assert values == df.a.to_list()
//  [python]
def test_applymap_function_runs_once():
    df = DataFrame({"a": [1, 2, 3]})
    values = []  # Save values function is applied to

    def reducing_function(val):
        values.append(val)

    def non_reducing_function(val):
        values.append(val)
        return val

    for func in [reducing_function, non_reducing_function]:
        del values[:]

        df.map(func)
        assert values == df.a.to_list()
//  [python]
def test_applymap_on_empty_dataframe(self):
        LOG.info("test_applymap_on_empty_dataframe")
        df = pd.DataFrame(columns=["x", "y"])
        pd_val = df.applymap(math_vec_square)
        swifter_val = df.swifter.applymap(math_vec_square)
        self.assertEqual(pd_val, swifter_val)
//  [python]
def test_applymap_on_empty_dataframe(self):
        LOG.info("test_applymap_on_empty_dataframe")
        df = pd.DataFrame(columns=["x", "y"])
        pd_val = df.map(math_vec_square)
        swifter_val = df.swifter.map(math_vec_square)
        self.assertEqual(pd_val, swifter_val)
//  [python]
def test_nonvectorized_math_applymap_on_small_dataframe(self):
        LOG.info("test_nonvectorized_math_applymap_on_small_dataframe")
        df = pd.DataFrame({"x": np.random.normal(size=1000), "y": np.random.uniform(size=1000)})
        pd_val = df.applymap(math_foo)
        swifter_val = df.swifter.set_npartitions(4).applymap(math_foo)
        self.assertEqual(pd_val, swifter_val)
//  [python]
def test_nonvectorized_math_applymap_on_small_dataframe(self):
        LOG.info("test_nonvectorized_math_applymap_on_small_dataframe")
        df = pd.DataFrame({"x": np.random.normal(size=1000), "y": np.random.uniform(size=1000)})
        pd_val = df.map(math_foo)
        swifter_val = df.swifter.set_npartitions(4).map(math_foo)
        self.assertEqual(pd_val, swifter_val)
//  [python]
def test_applymap_box():
    # ufunc will not be boxed. Same test cases as the test_map_box
    df = DataFrame(
        {
            "a": [Timestamp("2011-01-01"), Timestamp("2011-01-02")],
            "b": [
                Timestamp("2011-01-01", tz="US/Eastern"),
                Timestamp("2011-01-02", tz="US/Eastern"),
            ],
            "c": [pd.Timedelta("1 days"), pd.Timedelta("2 days")],
            "d": [
                pd.Period("2011-01-01", freq="M"),
                pd.Period("2011-01-02", freq="M"),
            ],
        }
    )

    result = df.applymap(lambda x: type(x).__name__)
    expected = DataFrame(
        {
            "a": ["Timestamp", "Timestamp"],
            "b": ["Timestamp", "Timestamp"],
            "c": ["Timedelta", "Timedelta"],
            "d": ["Period", "Period"],
        }
    )
    tm.assert_frame_equal(result, expected)
//  [python]
def test_applymap_box():
    # ufunc will not be boxed. Same test cases as the test_map_box
    df = DataFrame(
        {
            "a": [Timestamp("2011-01-01"), Timestamp("2011-01-02")],
            "b": [
                Timestamp("2011-01-01", tz="US/Eastern"),
                Timestamp("2011-01-02", tz="US/Eastern"),
            ],
            "c": [pd.Timedelta("1 days"), pd.Timedelta("2 days")],
            "d": [
                pd.Period("2011-01-01", freq="M"),
                pd.Period("2011-01-02", freq="M"),
            ],
        }
    )

    result = df.map(lambda x: type(x).__name__)
    expected = DataFrame(
        {
            "a": ["Timestamp", "Timestamp"],
            "b": ["Timestamp", "Timestamp"],
            "c": ["Timedelta", "Timedelta"],
            "d": ["Period", "Period"],
        }
    )
    tm.assert_frame_equal(result, expected)
//  [python]
def test_nonvectorized_math_applymap_on_small_dataframe_no_progress_bar(self):
        LOG.info("test_nonvectorized_math_applymap_on_small_dataframe_no_progress_bar")
        df = pd.DataFrame({"x": np.random.normal(size=1000), "y": np.random.uniform(size=1000)})
        pd_val = df.applymap(math_foo)
        swifter_val = df.swifter.progress_bar(enable=False).applymap(math_foo)
        self.assertEqual(pd_val, swifter_val)
//  [python]
def test_nonvectorized_math_applymap_on_small_dataframe_no_progress_bar(self):
        LOG.info("test_nonvectorized_math_applymap_on_small_dataframe_no_progress_bar")
        df = pd.DataFrame({"x": np.random.normal(size=1000), "y": np.random.uniform(size=1000)})
        pd_val = df.map(math_foo)
        swifter_val = df.swifter.progress_bar(enable=False).map(math_foo)
        self.assertEqual(pd_val, swifter_val)
//  [python]
def test_apply_type():
    # GH 46719
    df = DataFrame(
        {"col1": [3, "string", float], "col2": [0.25, datetime(2020, 1, 1), np.nan]},
        index=["a", "b", "c"],
    )

    # applymap
    result = df.applymap(type)
    expected = DataFrame(
        {"col1": [int, str, type], "col2": [float, datetime, float]},
        index=["a", "b", "c"],
    )
    tm.assert_frame_equal(result, expected)

    # axis=0
    result = df.apply(type, axis=0)
    expected = Series({"col1": Series, "col2": Series})
    tm.assert_series_equal(result, expected)

    # axis=1
    result = df.apply(type, axis=1)
    expected = Series({"a": Series, "b": Series, "c": Series})
    tm.assert_series_equal(result, expected)
//  [python]
def test_apply_type():
    # GH 46719
    df = DataFrame(
        {"col1": [3, "string", float], "col2": [0.25, datetime(2020, 1, 1), np.nan]},
        index=["a", "b", "c"],
    )

    # applymap
    result = df.map(type)
    expected = DataFrame(
        {"col1": [int, str, type], "col2": [float, datetime, float]},
        index=["a", "b", "c"],
    )
    tm.assert_frame_equal(result, expected)

    # axis=0
    result = df.apply(type, axis=0)
    expected = Series({"col1": Series, "col2": Series})
    tm.assert_series_equal(result, expected)

    # axis=1
    result = df.apply(type, axis=1)
    expected = Series({"a": Series, "b": Series, "c": Series})
    tm.assert_series_equal(result, expected)
//  [python]
def test_applymap():
    df = pd.DataFrame({'x': [1, 2, 3, 4], 'y': [10, 20, 30, 40]})
    ddf = dd.from_pandas(df, npartitions=2)
    assert_eq(ddf.applymap(lambda x: x + 1), df.applymap(lambda x: x + 1))

    assert_eq(ddf.applymap(lambda x: (x, x)), df.applymap(lambda x: (x, x)))
//  [python]
def test_applymap():
    df = pd.DataFrame({'x': [1, 2, 3, 4], 'y': [10, 20, 30, 40]})
    ddf = dd.from_pandas(df, npartitions=2)
    assert_eq(ddf.map(lambda x: x + 1), df.map(lambda x: x + 1))

    assert_eq(ddf.map(lambda x: (x, x)), df.map(lambda x: (x, x)))
//  [python]
def test_map_na_action(self):
    # Replicates a doctest for na_action which is incompatible with
    # doctest framework
    df = pd.DataFrame([[pd.NA, 2.12], [3.356, 4.567]])
    self._run_test(
        lambda df: df.map(lambda x: len(str(x)), na_action='ignore'),
        df,
        # TODO: generate proxy using naive type inference on fn
        check_proxy=False)
//  [python]
def oc_results_df(oc_res, oc_res_format: str = None):
    rows_and_columns = opencypher_get_rows_and_columns(oc_res, oc_res_format)
    if rows_and_columns:
        results_df = pd.DataFrame(rows_and_columns['rows'])
        results_df = results_df.astype(str)
        results_df = results_df.applymap(lambda x: encode_html_chars(x))
        col_0_value = range(1, len(results_df) + 1)
        results_df.insert(0, "#", col_0_value)
        for col_index, col_name in enumerate(rows_and_columns['columns']):
            results_df.rename({results_df.columns[col_index + 1]: col_name},
                              axis='columns',
                              inplace=True)
        has_results = True
    else:
        results_df = None
        has_results = False
    return results_df, has_results
//  [python]
def oc_results_df(oc_res, oc_res_format: str = None):
    rows_and_columns = opencypher_get_rows_and_columns(oc_res, oc_res_format)
    if rows_and_columns:
        results_df = pd.DataFrame(rows_and_columns['rows'])
        results_df = results_df.astype(str)
        results_df = results_df.apply(lambda x: x.map(encode_html_chars))
        col_0_value = range(1, len(results_df) + 1)
        results_df.insert(0, "#", col_0_value)
        for col_index, col_name in enumerate(rows_and_columns['columns']):
            results_df.rename({results_df.columns[col_index + 1]: col_name},
                              axis='columns',
                              inplace=True)
        has_results = True
    else:
        results_df = None
        has_results = False
    return results_df, has_results
//  [python]
def test_applymap(self):
        applied = self.frame.applymap(lambda x: x * 2)
        assert_frame_equal(applied, self.frame * 2)
        result = self.frame.applymap(type)

        # GH #465, function returning tuples
        result = self.frame.applymap(lambda x: (x, x))
        tm.assertIsInstance(result['A'][0], tuple)

        # GH 2909, object conversion to float in constructor?
        df = DataFrame(data=[1,'a'])
        result = df.applymap(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        df = DataFrame(data=[1.,'a'])
        result = df.applymap(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        # GH2786
        df  = DataFrame(np.random.random((3,4)))
        df2 = df.copy()
        cols = ['a','a','a','a']
        df.columns = cols

        expected = df2.applymap(str)
        expected.columns = cols
        result = df.applymap(str)
        assert_frame_equal(result,expected)

        # datetime/timedelta
        df['datetime'] = Timestamp('20130101')
        df['timedelta'] = Timedelta('1 min')
        result = df.applymap(str)
        for f in ['datetime','timedelta']:
            self.assertEqual(result.loc[0,f],str(df.loc[0,f]))
//  [python]
def test_applymap(self):
        applied = self.frame.map(lambda x: x * 2)
        assert_frame_equal(applied, self.frame * 2)
        result = self.frame.map(type)

        # GH #465, function returning tuples
        result = self.frame.map(lambda x: (x, x))
        tm.assertIsInstance(result['A'][0], tuple)

        # GH 2909, object conversion to float in constructor?
        df = DataFrame(data=[1,'a'])
        result = df.map(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        df = DataFrame(data=[1.,'a'])
        result = df.map(lambda x: x)
        self.assertEqual(result.dtypes[0], object)

        # GH2786
        df  = DataFrame(np.random.random((3,4)))
        df2 = df.copy()
        cols = ['a','a','a','a']
        df.columns = cols

        expected = df2.map(str)
        expected.columns = cols
        result = df.map(str)
        assert_frame_equal(result,expected)

        # datetime/timedelta
        df['datetime'] = Timestamp('20130101')
        df['timedelta'] = Timedelta('1 min')
        result = df.map(str)
        for f in ['datetime','timedelta']:
            self.assertEqual(result.loc[0,f],str(df.loc[0,f]))
//  [python]
def test_applymap():
    df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]})
    ddf = dd.from_pandas(df, npartitions=2)
    msg = "DataFrame.applymap has been deprecated"
    if PANDAS_GE_210:
        with pytest.warns(FutureWarning, match=msg):
            ddf_result = ddf.applymap(lambda x: x + 1)
        with pytest.warns(FutureWarning, match=msg):
            pdf_result = df.applymap(lambda x: x + 1)
        assert_eq(ddf_result, pdf_result)

        with pytest.warns(FutureWarning, match=msg):
            ddf_result = ddf.applymap(lambda x: (x, x))
        with pytest.warns(FutureWarning, match=msg):
            pdf_result = df.applymap(lambda x: (x, x))
        assert_eq(ddf_result, pdf_result)
    else:
        ddf_result = ddf.applymap(lambda x: x + 1)
        pdf_result = df.applymap(lambda x: x + 1)
        assert_eq(ddf_result, pdf_result)

        ddf_result = ddf.applymap(lambda x: (x, x))
        pdf_result = df.applymap(lambda x: (x, x))
        assert_eq(ddf_result, pdf_result)
//  [python]
def test_applymap():
    df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]})
    ddf = dd.from_pandas(df, npartitions=2)
    msg = "DataFrame.applymap has been deprecated"
    if PANDAS_GE_210:
        with pytest.warns(FutureWarning, match=msg):
            ddf_result = ddf.apply(lambda x: x + 1)
        with pytest.warns(FutureWarning, match=msg):
            pdf_result = df.apply(lambda x: x + 1)
        assert_eq(ddf_result, pdf_result)

        with pytest.warns(FutureWarning, match=msg):
            ddf_result = ddf.apply(lambda x: (x, x))
        with pytest.warns(FutureWarning, match=msg):
            pdf_result = df.apply(lambda x: (x, x))
        assert_eq(ddf_result, pdf_result)
    else:
        ddf_result = ddf.apply(lambda x: x + 1)
        pdf_result = df.apply(lambda x: x + 1)
        assert_eq(ddf_result, pdf_result)

        ddf_result = ddf.apply(lambda x: (x, x))
        pdf_result = df.apply(lambda x: (x, x))
        assert_eq(ddf_result, pdf_result)
//  [python]
def test_dataframe_map(na_action):
    df = pd.DataFrame({"x": [1, 2, 3, np.nan], "y": [10, 20, 30, 40]})
    ddf = dd.from_pandas(df, npartitions=2)
    assert_eq(
        ddf.map(lambda x: x + 1, na_action=na_action),
        df.applymap(lambda x: x + 1),
    )
    assert_eq(ddf.map(lambda x: (x, x)), df.applymap(lambda x: (x, x)))
//  [python]
def test_dataframe_map(na_action):
    df = pd.DataFrame({"x": [1, 2, 3, np.nan], "y": [10, 20, 30, 40]})
    ddf = dd.from_pandas(df, npartitions=2)
    assert_eq(
        ddf.map(lambda x: x + 1, na_action=na_action),
        df.map(lambda x: x + 1, na_action=na_action),
    )
    assert_eq(ddf.map(lambda x: (x, x)), df.map(lambda x: (x, x)))
//  [python]
def show_corrs(
    factors: list[pd.DataFrame] = None,
    factor_names: list[str] = None,
    print_bool: bool = True,
    show_percent: bool = True,
) -> pd.DataFrame:
    """展示很多因子的截面相关性"""
    corrs = []
    for i in range(len(factors)):
        main_i = factors[i]
        follows = factors[i + 1 :]
        corr = [show_corr(main_i, i, plt_plot=False) for i in follows]
        corr = [np.nan] * (i + 1) + corr
        corrs.append(corr)
    if factor_names is None:
        factor_names = [f"fac{i}" for i in list(range(1, len(factors) + 1))]
    corrs = pd.DataFrame(corrs, columns=factor_names, index=factor_names)
    np.fill_diagonal(corrs.to_numpy(), 1)
    if show_percent:
        pcorrs = corrs.applymap(to_percent)
    else:
        pcorrs = corrs.copy()
    if print_bool:
        print(pcorrs)
    return corrs
//  [python]
def show_corrs(
    factors: list[pd.DataFrame] = None,
    factor_names: list[str] = None,
    print_bool: bool = True,
    show_percent: bool = True,
) -> pd.DataFrame:
    """展示很多因子的截面相关性"""
    corrs = []
    for i in range(len(factors)):
        main_i = factors[i]
        follows = factors[i + 1 :]
        corr = [show_corr(main_i, i, plt_plot=False) for i in follows]
        corr = [np.nan] * (i + 1) + corr
        corrs.append(corr)
    if factor_names is None:
        factor_names = [f"fac{i}" for i in list(range(1, len(factors) + 1))]
    corrs = pd.DataFrame(corrs, columns=factor_names, index=factor_names)
    np.fill_diagonal(corrs.to_numpy(), 1)
    if show_percent:
        pcorrs = corrs.map(to_percent)
    else:
        pcorrs = corrs.copy()
    if print_bool:
        print(pcorrs)
    return corrs
//  [python]
def test_pad(self):
        pdf = pd.DataFrame(
            {
                "A": [None, 3, None, None],
                "B": [2, 4, None, 3],
                "C": [None, None, None, 1],
                "D": [0, 1, 5, 4],
            },
            columns=["A", "B", "C", "D"],
        )
        psdf = ps.from_pandas(pdf)

        self.assert_eq(pdf.pad(), psdf.pad())

        # Test `inplace=True`
        pdf.pad(inplace=True)
        psdf.pad(inplace=True)
        self.assert_eq(pdf, psdf)
//  [python]
def test_pad(self):
        pdf = pd.DataFrame(
            {
                "A": [None, 3, None, None],
                "B": [2, 4, None, 3],
                "C": [None, None, None, 1],
                "D": [0, 1, 5, 4],
            },
            columns=["A", "B", "C", "D"],
        )
        psdf = ps.from_pandas(pdf)

        self.assert_eq(pdf.ffill(), psdf.ffill())

        # Test `inplace=True`
        pdf.ffill(inplace=True)
        psdf.ffill(inplace=True)
        self.assert_eq(pdf, psdf)
//  [python]
def test_interpolate_creates_copy(using_copy_on_write):
    # GH#51126
    df = DataFrame({"a": [1.5, np.nan, 3]})
    view = df[:]
    expected = df.copy()

    df.fillna(method='ffill', inplace=True)
    df.iloc[0, 0] = 100.5

    if using_copy_on_write:
        tm.assert_frame_equal(view, expected)
    else:
        expected = DataFrame({"a": [100.5, 1.5, 3]})
        tm.assert_frame_equal(view, expected)
//  [python]
def test_interpolate_creates_copy(using_copy_on_write):
    # GH#51126
    df = DataFrame({"a": [1.5, np.nan, 3]})
    view = df[:]
    expected = df.copy()

    df.ffill(inplace=True)
    df.iloc[0, 0] = 100.5

    if using_copy_on_write:
        tm.assert_frame_equal(view, expected)
    else:
        expected = DataFrame({"a": [100.5, 1.5, 3]})
        tm.assert_frame_equal(view, expected)