Skip to content

Commit

Permalink
ENH: Support strings containing '%' in add_prefix/add_suffix (pandas-…
Browse files Browse the repository at this point in the history
  • Loading branch information
jschendel authored and jreback committed Aug 3, 2017
1 parent 0c4bc05 commit 9b07ef4
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ Other Enhancements
- :func:`date_range` now accepts 'YS' in addition to 'AS' as an alias for start of year (:issue:`9313`)
- :func:`date_range` now accepts 'Y' in addition to 'A' as an alias for end of year (:issue:`9313`)
- Integration with `Apache Parquet <https://parquet.apache.org/>`__, including a new top-level :func:`read_parquet` and :func:`DataFrame.to_parquet` method, see :ref:`here <io.parquet>`.
- :func:`DataFrame.add_prefix` and :func:`DataFrame.add_suffix` now accept strings containing the '%' character. (:issue:`17151`)

.. _whatsnew_0210.api_breaking:

Expand Down
5 changes: 3 additions & 2 deletions pandas/core/internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import operator
from datetime import datetime, timedelta, date
from collections import defaultdict
from functools import partial

import numpy as np

Expand Down Expand Up @@ -2959,11 +2960,11 @@ def rename_axis(self, mapper, axis, copy=True, level=None):
return obj

def add_prefix(self, prefix):
f = (str(prefix) + '%s').__mod__
f = partial('{prefix}{}'.format, prefix=prefix)
return self.rename_axis(f, axis=0)

def add_suffix(self, suffix):
f = ('%s' + str(suffix)).__mod__
f = partial('{}{suffix}'.format, suffix=suffix)
return self.rename_axis(f, axis=0)

@property
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/frame/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ def test_add_prefix_suffix(self):
expected = pd.Index(['%s#foo' % c for c in self.frame.columns])
tm.assert_index_equal(with_suffix.columns, expected)

with_pct_prefix = self.frame.add_prefix('%')
expected = pd.Index(['%{}'.format(c) for c in self.frame.columns])
tm.assert_index_equal(with_pct_prefix.columns, expected)

with_pct_suffix = self.frame.add_suffix('%')
expected = pd.Index(['{}%'.format(c) for c in self.frame.columns])
tm.assert_index_equal(with_pct_suffix.columns, expected)


class TestDataFrameMisc(SharedWithSparse, TestData):

Expand Down

0 comments on commit 9b07ef4

Please sign in to comment.