From a3f60a4531be7f47bbbe469a5cd2666f978006ad Mon Sep 17 00:00:00 2001 From: David Hensle Date: Thu, 8 Feb 2024 11:33:51 -0800 Subject: [PATCH] added unit test for df_from_dict indexing --- activitysim/core/test/test_util.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/activitysim/core/test/test_util.py b/activitysim/core/test/test_util.py index ae9b4fa83..415ec1f9e 100644 --- a/activitysim/core/test/test_util.py +++ b/activitysim/core/test/test_util.py @@ -7,7 +7,7 @@ import pandas.testing as pdt import pytest -from ..util import other_than, quick_loc_df, quick_loc_series, reindex +from ..util import other_than, quick_loc_df, quick_loc_series, reindex, df_from_dict @pytest.fixture(scope="module") @@ -62,3 +62,30 @@ def test_quick_loc_series(): assert list(quick_loc_series(loc_list, series)) == attrib_list assert list(quick_loc_series(loc_list, series)) == list(series.loc[loc_list]) + + +def test_df_from_dict(): + + index = [1, 2, 3, 4, 5] + df = pd.DataFrame({"attrib": [1, 2, 2, 3, 1]}, index=index) + + # scramble index order for one expression and not the other + sorted = df.eval("attrib.sort_values()") + not_sorted = df.eval("attrib * 1") + + # check above expressions + pdt.assert_series_equal( + sorted, pd.Series([1, 1, 2, 2, 3], index=[1, 5, 2, 3, 4]), check_names=False + ) + pdt.assert_series_equal(not_sorted, df.attrib, check_names=False) + + # create a new dataframe from the above expressions + values = {"sorted": sorted, "not_sorted": not_sorted} + new_df = df_from_dict(values, index) + + # index should become unscrambed and back to the same order as before + expected_df = pd.DataFrame( + {"sorted": [1, 2, 2, 3, 1], "not_sorted": [1, 2, 2, 3, 1]}, index=index + ) + + pdt.assert_frame_equal(new_df, expected_df)