|
| 1 | +import pytest # noqa |
| 2 | + |
| 3 | +import pandas as pd |
| 4 | +import pandas._testing as tm |
| 5 | + |
| 6 | + |
| 7 | +class TestCaseWhen: |
| 8 | + def test_case_when_multiple_conditions_callable(self): |
| 9 | + df = pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6])) |
| 10 | + result = df.assign( |
| 11 | + new_column=pd.case_when( |
| 12 | + lambda x: x.a == 1, |
| 13 | + "first", |
| 14 | + lambda x: (x.a > 1) & (x.b == 5), |
| 15 | + "second", |
| 16 | + ) |
| 17 | + ) |
| 18 | + expected = df.assign(new_column=["first", "second", None]) |
| 19 | + tm.assert_frame_equal(result, expected) |
| 20 | + |
| 21 | + def test_case_when_multiple_conditions_array_series(self): |
| 22 | + df = pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6])) |
| 23 | + result = df.assign( |
| 24 | + new_column=pd.case_when( |
| 25 | + [True, False, False], |
| 26 | + "first", |
| 27 | + pd.Series([False, True, False]), |
| 28 | + "second", |
| 29 | + ) |
| 30 | + ) |
| 31 | + expected = df.assign(new_column=["first", "second", None]) |
| 32 | + tm.assert_frame_equal(result, expected) |
| 33 | + |
| 34 | + def test_case_when_multiple_conditions_callable_default(self): |
| 35 | + df = pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6])) |
| 36 | + result = df.assign( |
| 37 | + new_column=pd.case_when( |
| 38 | + lambda x: x.a == 1, |
| 39 | + "first", |
| 40 | + lambda x: (x.a > 1) & (x.b == 5), |
| 41 | + "second", |
| 42 | + default="default", |
| 43 | + ) |
| 44 | + ) |
| 45 | + expected = df.assign(new_column=["first", "second", "default"]) |
| 46 | + tm.assert_frame_equal(result, expected) |
| 47 | + |
| 48 | + def test_case_when_multiple_conditions_callable_default_series(self): |
| 49 | + df = pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6])) |
| 50 | + result = df.assign( |
| 51 | + new_column=pd.case_when( |
| 52 | + lambda x: x.a == 1, |
| 53 | + "first", |
| 54 | + lambda x: (x.a > 1) & (x.b == 5), |
| 55 | + "second", |
| 56 | + default=df.b, |
| 57 | + ) |
| 58 | + ) |
| 59 | + expected = df.assign(new_column=["first", "second", "6"]) |
| 60 | + tm.assert_frame_equal(result, expected) |
0 commit comments