Pandas series.rename给出TypeError:' str' object不可调用错误

时间:2016-09-15 19:02:06

标签: python python-2.7 pandas dataframe

我无法弄清楚为什么会这样。我知道如果我有函数名称" shadowed"不知何故。但是我怎么能在这种情况下呢?

如果我在终端中打开iPython,然后输入:

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

我得到TypeError:' str'对象不可调用。可能是什么原因造成的?

错误消息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

测试示例here的参考。

2 个答案:

答案 0 :(得分:0)

太棒了,多亏了Nickil Maveli,他指出我需要0.18.1,现在它可以了。我的错误思考brew upgrade会让我找到最新的版本。

答案 1 :(得分:0)

如果熊猫版本低于0.18.1,并且您无法升级,则直接设置name属性可达到预期效果:

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