Path: blob/main/py-polars/tests/unit/dataframe/test_vstack.py
6939 views
import pytest12import polars as pl3from polars.exceptions import SchemaError, ShapeError4from polars.testing import assert_frame_equal567@pytest.fixture8def df1() -> pl.DataFrame:9return pl.DataFrame({"foo": [1, 2], "bar": [6, 7], "ham": ["a", "b"]})101112@pytest.fixture13def df2() -> pl.DataFrame:14return pl.DataFrame({"foo": [3, 4], "bar": [8, 9], "ham": ["c", "d"]})151617def test_vstack(df1: pl.DataFrame, df2: pl.DataFrame) -> None:18result = df1.vstack(df2)19expected = pl.DataFrame(20{"foo": [1, 2, 3, 4], "bar": [6, 7, 8, 9], "ham": ["a", "b", "c", "d"]}21)22assert_frame_equal(result, expected)232425def test_vstack_in_place(df1: pl.DataFrame, df2: pl.DataFrame) -> None:26df1.vstack(df2, in_place=True)27expected = pl.DataFrame(28{"foo": [1, 2, 3, 4], "bar": [6, 7, 8, 9], "ham": ["a", "b", "c", "d"]}29)30assert_frame_equal(df1, expected)313233def test_vstack_self(df1: pl.DataFrame) -> None:34result = df1.vstack(df1)35expected = pl.DataFrame(36{"foo": [1, 2, 1, 2], "bar": [6, 7, 6, 7], "ham": ["a", "b", "a", "b"]}37)38assert_frame_equal(result, expected)394041def test_vstack_self_in_place(df1: pl.DataFrame) -> None:42df1.vstack(df1, in_place=True)43expected = pl.DataFrame(44{"foo": [1, 2, 1, 2], "bar": [6, 7, 6, 7], "ham": ["a", "b", "a", "b"]}45)46assert_frame_equal(df1, expected)474849def test_vstack_column_number_mismatch(df1: pl.DataFrame) -> None:50df2 = df1.drop("ham")5152with pytest.raises(ShapeError):53df1.vstack(df2)545556def test_vstack_column_name_mismatch(df1: pl.DataFrame) -> None:57df2 = df1.with_columns(pl.col("foo").alias("oof"))5859with pytest.raises(ShapeError):60df1.vstack(df2)616263def test_vstack_with_null_column() -> None:64df1 = pl.DataFrame({"x": [3.5]}, schema={"x": pl.Float64})65df2 = pl.DataFrame({"x": [None]}, schema={"x": pl.Null})6667result = df1.vstack(df2)68expected = pl.DataFrame({"x": [3.5, None]}, schema={"x": pl.Float64})6970assert_frame_equal(result, expected)7172with pytest.raises(SchemaError):73df2.vstack(df1)747576def test_vstack_with_nested_nulls() -> None:77a = pl.DataFrame({"x": [[3.5]]}, schema={"x": pl.List(pl.Float32)})78b = pl.DataFrame({"x": [[None]]}, schema={"x": pl.List(pl.Null)})7980out = a.vstack(b)81expected = pl.DataFrame({"x": [[3.5], [None]]}, schema={"x": pl.List(pl.Float32)})82assert_frame_equal(out, expected)838485def test_vstack_bad_input_type() -> None:86a = pl.DataFrame({"x": [1, 2, 3]})87b = pl.DataFrame({"x": [4, 5, 6]})8889with pytest.raises(90TypeError,91match="expected `other` .*to be a 'DataFrame'.* not 'Series'",92):93a.vstack(pl.Series(b)) # type: ignore[arg-type]9495with pytest.raises(96TypeError,97match="expected `other` .*to be a 'DataFrame'.* not 'LazyFrame'",98):99a.vstack(b.lazy()) # type: ignore[arg-type]100101class DummyDataFrameSubclass(pl.DataFrame):102pass103104b = DummyDataFrameSubclass(b)105106a = a.vstack(b)107108109