Skip to content

Commit

Permalink
Merge pull request #76 from martindurant/add_rename
Browse files Browse the repository at this point in the history
Add "rename" method
  • Loading branch information
martindurant authored Aug 15, 2024
2 parents 6d46786 + 664503b commit e8c12a3
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
13 changes: 13 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,19 @@ define will appear on the ``.ak`` accessor or can be used for ufunc and
operator overloads.


Sub-accessors
~~~~~~~~~~~~~

As an alternative to the object-oriented behaviours, developers may create
accessor namespaces that appear under ``.ak`` similar to the the builtin
``.ak.str`` (strings ops) snd ``.ak.dt`` (datetime ops) included already.

One experimental proof-of-concept is `akimbo-ip`_, which provides fast vectorised
manipulations of IPv4/6 addresses and networks; and by using this through
the ``akimbo`` system, you can apply these methods to ragged/nested dataframes.

.. _akimbo-ip: https://github.com/intake/akimbo-ip

.. toctree::
:maxdepth: 1
:caption: User Guide
Expand Down
24 changes: 24 additions & 0 deletions src/akimbo/mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,30 @@ def register_accessor(cls, name, klass):
# TODO: check clobber?
cls.subaccessors[name] = klass

def rename(self, where, to):
"""Assign new field name to given location in the structure
Parameters
----------
where: str | tuple[str]
location we would like to rename
to: str
new name
"""
arr = self.array
lay = ak.copy(arr.layout)
where = list(where) if isinstance(where, tuple) else [where]
parent = None
bit = lay
while where:
if getattr(bit, "contents", None):
this = bit.fields.index(where.pop(0))
parent, bit = bit, bit.contents[this]
else:
parent, bit = bit, bit.content
parent.fields[this] = to
return self.to_output(ak.Array(lay))

def merge(self):
"""Make a single complex series out of the columns of a dataframe"""
if not self.is_dataframe(self._obj):
Expand Down
14 changes: 14 additions & 0 deletions tests/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,17 @@ def test_to_autoarrow():
s2 = s.ak.to_output()
assert s2.tolist() == a
assert "pyarrow" in str(s2.dtype)


def test_rename():
a = [{"a": [{"b": {"c": 0}}] * 2}] * 3
s = pd.Series(a)

s2 = s.ak.rename(("a", "b"), "d")
assert s2.tolist() == [{"a": [{"d": {"c": 0}}] * 2}] * 3

s2 = s.ak.rename("a", "d")
assert s2.tolist() == [{"d": [{"b": {"c": 0}}] * 2}] * 3

s2 = s.ak.rename(("a", "b", "c"), "d")
assert s2.tolist() == [{"a": [{"b": {"d": 0}}] * 2}] * 3

0 comments on commit e8c12a3

Please sign in to comment.