johnblund
johnblund

Reputation: 402

Pandas series.rename gives TypeError: 'str' object is not callable error

I can't figure out why this happens. I know this could happen if I have the function name "shadowed" somehow. But how could I in this scenario?

If I open iPython in my terminal and then type:

import pandas as pd
a = pd.Series([1,2,3,4])
a.rename("test")

I get TypeError: 'str' object is not callable. What could be the causes of this?

Longer error msg:

   /usr/local/lib/python2.7/site-packages/pandas/core/series.pyc in rename(self, index, **kwargs)
   2262     @Appender(generic._shared_docs['rename'] % _shared_doc_kwargs)
   2263     def rename(self, index=None, **kwargs):
-> 2264         return super(Series, self).rename(index=index, **kwargs)
   2265
   2266     @Appender(generic._shared_docs['reindex'] % _shared_doc_kwargs)

/usr/local/lib/python2.7/site-packages/pandas/core/generic.pyc in rename(self, *args, **kwargs)
    604
    605             baxis = self._get_block_manager_axis(axis)
--> 606             result._data = result._data.rename_axis(f, axis=baxis, copy=copy)
    607             result._clear_item_cache()
    608

/usr/local/lib/python2.7/site-packages/pandas/core/internals.pyc in rename_axis(self, mapper, axis, copy)
   2586         """
   2587         obj = self.copy(deep=copy)
-> 2588         obj.set_axis(axis, _transform_index(self.axes[axis], mapper))
   2589         return obj
   2590

/usr/local/lib/python2.7/site-packages/pandas/core/internals.pyc in _transform_index(index, func)
   4389         return MultiIndex.from_tuples(items, names=index.names)
   4390     else:
-> 4391         items = [func(x) for x in index]
   4392         return Index(items, name=index.name)
   4393

Reference for test example here.

Upvotes: 6

Views: 2662

Answers (2)

Justin Raymond
Justin Raymond

Reputation: 3558

If the pandas version is less than 0.18.1 and you cannot upgrade, setting the name attribute directly achieves the desired result:

s = pd.Series(list(range(2)), name='foo')
s
# 0    0
# 1   1
# Name: foo, dtype: int64
s.name = 'bar'
s
# 0    0
# 1    1
# Name: bar, dtype: int64

Upvotes: 0

johnblund
johnblund

Reputation: 402

Great, thanks to Nickil Maveli who pointed out I need 0.18.1, now it works. My mistake thinking brew upgrade would have sorted out me having the latest version.

Upvotes: 1

Related Questions