Skip to content

Commit

Permalink
added index checks
Browse files Browse the repository at this point in the history
  • Loading branch information
kthyng committed Sep 8, 2023
1 parent ff16ed1 commit b82de85
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions cf_pandas/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,23 @@ def __setitem__(self, key: str, values: Union[Sequence, Series]):
# make new column
self._obj[key] = values
# return self._obj[key]
elif isinstance(col, pd.Index):
# which of possible multi index it is
# does single and multi index need to be separated?
# ilev = self._obj.index.names.index(col.name)
# self._obj.index = self._obj.index.set_levels(values, level=ilev)

# loop over levels in index so we know which level to replace
inds = []
for lev in range(self._obj.index.nlevels):
ind = self._obj.index.get_level_values(lev)
if self._obj.index.names[lev] == col.name:
save_type = type(col)
ind = save_type(values)
ind.name = col.name
inds.append(ind)
self._obj = self._obj.set_index(inds)

else:
raise ValueError("Setting item only works if key matches one column only.")

Expand Down

0 comments on commit b82de85

Please sign in to comment.