Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow rename() for model and scenarios #87

Merged
merged 6 commits into from
Sep 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

# Next Release

- (#87)[https://github.com/IAMconsortium/pyam/pull/87] Extending `rename()` to work with model and scenario names
- (#85)[https://github.com/IAMconsortium/pyam/pull/85] Improved functionality for importing metadata and bugfix for filtering for strings if `nan` values exist in metadata
- (#83)[https://github.com/IAMconsortium/pyam/pull/83] Extending `filter_by_meta()` to work with non-matching indices between `df` and `data
- (#81)[https://github.com/IAMconsortium/pyam/pull/81] Bug-fix when using `set_meta()` with unnamed pd.Series and no `name` kwarg
Expand Down
19 changes: 14 additions & 5 deletions pyam/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,9 @@ def validate(self, criteria={}, exclude_on_fail=False):
return df

def rename(self, mapping, inplace=False):
"""Rename and aggregate column entries using groupby.sum()
"""Rename and aggregate column entries using `groupby.sum()` on values.
When renaming models or scenarios, the uniqueness of the index must be
maintained, and the function will raise an error otherwise.

Parameters
----------
Expand All @@ -445,10 +447,17 @@ def rename(self, mapping, inplace=False):
if True, do operation inplace and return None
"""
ret = copy.deepcopy(self) if not inplace else self
for col in mapping:
if col not in ['region', 'variable', 'unit']:
raise ValueError('renaming by {} not supported!'.format(col))
ret.data.loc[:, col] = self.data.loc[:, col].replace(mapping[col])
for col, _mapping in mapping.items():
if col in ['model', 'scenario']:
index = pd.DataFrame(index=ret.meta.index).reset_index()
index.loc[:, col] = index.loc[:, col].replace(_mapping)
if index.duplicated().any():
raise ValueError('Renaming to non-unique {} index!'
.format(col))
ret.meta.index = index.set_index(META_IDX).index
elif col not in ['region', 'variable', 'unit']:
raise ValueError('Renaming by {} not supported!'.format(col))
ret.data.loc[:, col] = ret.data.loc[:, col].replace(_mapping)

ret.data = ret.data.groupby(LONG_IDX).sum().reset_index()
if not inplace:
Expand Down
33 changes: 31 additions & 2 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from numpy import testing as npt

from pyam import IamDataFrame, plotting, validate, categorize, \
require_variable, check_aggregate, filter_by_meta, META_IDX
require_variable, check_aggregate, filter_by_meta, META_IDX, IAMC_IDX
from pyam.core import _meta_idx

from conftest import TEST_DATA_DIR
Expand Down Expand Up @@ -549,7 +549,7 @@ def test_48b():
pd.testing.assert_frame_equal(obs, exp, check_index_type=False)


def test_rename():
def test_rename_variable():
df = IamDataFrame(pd.DataFrame([
['model', 'scen', 'SST', 'test_1', 'unit', 1, 5],
['model', 'scen', 'SDN', 'test_2', 'unit', 2, 6],
Expand All @@ -572,6 +572,35 @@ def test_rename():
pd.testing.assert_frame_equal(obs, exp, check_index_type=False)


def test_rename_index_fail(meta_df):
mapping = {'scenario': {'a_scenario': 'a_scenario2'}}
pytest.raises(ValueError, meta_df.rename, mapping)


def test_rename_index(meta_df):
mapping = {'model': {'a_model': 'b_model'},
'scenario': {'a_scenario': 'b_scen'}}
obs = meta_df.rename(mapping)

# test data changes
exp = pd.DataFrame([
['b_model', 'b_scen', 'World', 'Primary Energy', 'EJ/y', 1., 6.],
['b_model', 'b_scen', 'World', 'Primary Energy|Coal', 'EJ/y', .5, 3.],
['b_model', 'a_scenario2', 'World', 'Primary Energy', 'EJ/y', 2., 7.],
], columns=['model', 'scenario', 'region', 'variable', 'unit', 2005, 2010]
).set_index(IAMC_IDX).sort_index()
exp.columns = exp.columns.map(int)
pd.testing.assert_frame_equal(obs.timeseries().sort_index(), exp)

# test meta changes
exp = pd.DataFrame([
['b_model', 'b_scen', False],
['b_model', 'a_scenario2', False],
], columns=['model', 'scenario', 'exclude']
).set_index(META_IDX)
pd.testing.assert_frame_equal(obs.meta, exp)


def test_convert_unit():
df = IamDataFrame(pd.DataFrame([
['model', 'scen', 'SST', 'test_1', 'A', 1, 5],
Expand Down