|
7 | 7 | import pandas.testing as pdt |
8 | 8 | import pytest |
9 | 9 |
|
10 | | -from ..util import other_than, quick_loc_df, quick_loc_series, reindex |
| 10 | +from ..util import other_than, quick_loc_df, quick_loc_series, reindex, df_from_dict |
11 | 11 |
|
12 | 12 |
|
13 | 13 | @pytest.fixture(scope="module") |
@@ -62,3 +62,30 @@ def test_quick_loc_series(): |
62 | 62 |
|
63 | 63 | assert list(quick_loc_series(loc_list, series)) == attrib_list |
64 | 64 | assert list(quick_loc_series(loc_list, series)) == list(series.loc[loc_list]) |
| 65 | + |
| 66 | + |
| 67 | +def test_df_from_dict(): |
| 68 | + |
| 69 | + index = [1, 2, 3, 4, 5] |
| 70 | + df = pd.DataFrame({"attrib": [1, 2, 2, 3, 1]}, index=index) |
| 71 | + |
| 72 | + # scramble index order for one expression and not the other |
| 73 | + sorted = df.eval("attrib.sort_values()") |
| 74 | + not_sorted = df.eval("attrib * 1") |
| 75 | + |
| 76 | + # check above expressions |
| 77 | + pdt.assert_series_equal( |
| 78 | + sorted, pd.Series([1, 1, 2, 2, 3], index=[1, 5, 2, 3, 4]), check_names=False |
| 79 | + ) |
| 80 | + pdt.assert_series_equal(not_sorted, df.attrib, check_names=False) |
| 81 | + |
| 82 | + # create a new dataframe from the above expressions |
| 83 | + values = {"sorted": sorted, "not_sorted": not_sorted} |
| 84 | + new_df = df_from_dict(values, index) |
| 85 | + |
| 86 | + # index should become unscrambed and back to the same order as before |
| 87 | + expected_df = pd.DataFrame( |
| 88 | + {"sorted": [1, 2, 2, 3, 1], "not_sorted": [1, 2, 2, 3, 1]}, index=index |
| 89 | + ) |
| 90 | + |
| 91 | + pdt.assert_frame_equal(new_df, expected_df) |
0 commit comments