Commit c187e6ed authored by PIOLLE's avatar PIOLLE
Browse files

added options for append method

parent a55986de
......@@ -206,9 +206,25 @@ class Feature(Dataset, ABC):
return dim_validity
def append(self, feature, prefix=None, fields=None):
def append(self,
prefix: str = None,
add_coords: bool = False,
as_new_dims: bool = False,
fields: str = None):
"""Append the fields from another feature
The fields can share the same coordinates and dimensions (if the added
feature is an overlay of the current feature). In such case the
shared coordinates of the added feature are not copied, unless
`add_coords` is set to True (in which case they are first prefixed
using `prefix`).
If the dimensions of the added field have unrelated to the current
feature (even if they have similar names), `as_new_dims` must be set
to True. The dimensions (and corresponding coordinates) are prefixed
with `prefix` and added to with the fields to the current feature.
feature (AbstractFeature derived class): the feature to append.
......@@ -216,21 +232,48 @@ class Feature(Dataset, ABC):
feature (to avoid conflicts with the existing fields of the
current feature).
add_coords: if True, add the feature coordinates as variables. If
false, they are not added.
as_new_dims: rename the field and coordinate dimensions with prefix
fields (list of str): a list of fieldnames specifying which fields
are to be appended. By default, all fields of the feature are
if as_new_dims and prefix is None:
raise ValueError(
"a valid prefix must be provided to rename the dimensions")
if add_coords and prefix is None:
raise ValueError(
"a valid prefix must be provided to add the coordinates")
added_fields = fields
if added_fields is None:
added_fields = feature.fieldnames
if add_coords:
# append fields
for fieldname in added_fields:
if fieldname in feature.fieldnames:
field = feature.get_field(fieldname).clone()
elif fieldname in feature.coords:
field = feature.get_coord(fieldname).clone()
raise ValueError("field {} not found in feature".format(
if prefix is not None:
if as_new_dims:
field._array = field._array.rename(
{_: '{}{}'.format(prefix, _) for _ in field.dims})
def get_values(self, *args, **kwargs):
......@@ -173,8 +173,14 @@ class TestFeature(unittest.TestCase):
# another feature of same dimensions & coordinates
feat2 = self.get_feature(self.define_base_feature())
# append
# append with shared dimension
feat.append(feat2, prefix="v2_")
for fieldname in feat2.fieldnames:
self.assertIn("v2_"+fieldname, feat.fieldnames)
np.allclose(feat.get_values(fieldname), feat2.get_values(fieldname))
# test append with unshared dimensions
feat = self.get_feature(self.define_base_feature())
feat.append(feat2, prefix="v2_", as_new_dims=True)
self.assertIn("v2_time", feat.dims)
self.assertIn("v2_time", feat.coordnames)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment