【问题标题】:Pandas series.rename gives TypeError: 'str' object is not callable errorPandas series.rename 给出 TypeError: 'str' object is not callable 错误
【发布时间】:2017-01-23 22:02:11
【问题描述】:

我不明白为什么会这样。我知道如果我以某种方式“隐藏”了函数名称,这可能会发生。但我怎么能在这种情况下呢?

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

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

我得到 TypeError: 'str' object is not callable。这可能是什么原因?

更长的错误消息:

   /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

【问题讨论】:

  • 您使用的是哪个版本的熊猫?
  • 嗨,这是我在 pd.__version__: u'0.17.1' 上的内容。我试过brew updatebrew upgrade 所以一切都应该是最新的。
  • 如果要将标量值输入到renameDocs,则需要升级到0.18.1或更高版本

标签: python python-2.7 pandas dataframe


【解决方案1】:

太好了,感谢 Nickil Maveli 指出我需要 0.18.1,现在它可以工作了。我错误地认为brew upgrade 会让我得到最新版本。

【讨论】:

    【解决方案2】:

    如果pandas版本低于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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2019-10-08
      • 2013-05-28
      • 2021-02-03
      • 2020-12-15
      • 2014-11-16
      相关资源
      最近更新 更多