python-3.x - AttributeError:“DataFrame”对象在熊猫中没有属性“droplevel”
问题描述
当我尝试从多索引 pandas 数据框中删除一个级别时,我收到一条奇怪的(据我所知)消息。
对于一个可重现的例子:
toy.to_json()
'{"["ISRG","EPS_diluted"]":{"2004-12-31":0.33,"2005-01-28":0.33,"2005-03-31":0.25,"2005-04-01":0.25,"2005-04-29":0.25},"["DHR","EPS_diluted"]":{"2004-12-31":0.67,"2005-01-28":0.67,"2005-03-31":0.67,"2005-04-01":0.58,"2005-04-29":0.58},"["BDX","EPS_diluted"]":{"2004-12-31":0.75,"2005-01-28":0.75,"2005-03-31":0.72,"2005-04-01":0.72,"2005-04-29":0.72},"["SYK","EPS_diluted"]":{"2004-12-31":0.4,"2005-01-28":0.4,"2005-03-31":0.42,"2005-04-01":0.42,"2005-04-29":0.42},"["BSX","EPS_diluted"]":{"2004-12-31":0.35,"2005-01-28":0.35,"2005-03-31":0.42,"2005-04-01":0.42,"2005-04-29":0.42},"["BAX","EPS_diluted"]":{"2004-12-31":0.18,"2005-01-28":0.18,"2005-03-31":0.36,"2005-04-01":0.36,"2005-04-29":0.36},"["EW","EPS_diluted"]":{"2004-12-31":0.4,"2005-01-28":0.4,"2005-03-31":0.5,"2005-04-01":0.5,"2005-04-29":0.5},"["MDT","EPS_diluted"]":{"2004-12-31":0.44,"2005-01-28":0.45,"2005-03-31":0.45,"2005-04-01":0.45,"2005-04-29":0.16},"["ABT","EPS_diluted"]":{"2004-12-31":0.63,"2005-01-28":0.63,"2005-03-31":0.53,"2005-04-01":0.53,"2005-04-29":0.53}}'
toy.droplevel(level = 1, axis = 1)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-33-982eee5ba162> in <module>()
----> 1 toy.droplevel(level = 1, axis = 1)
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
4370 if self._info_axis._can_hold_identifiers_and_holds_name(name):
4371 return self[name]
-> 4372 return object.__getattribute__(self, name)
4373
4374 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'droplevel'
解决方案
Problem is the use of an older pandas version, because if you check DataFrame.droplevel
:
New in version 0.24.0.
The solution is to use MultiIndex.droplevel
:
toy.columns = toy.columns.droplevel(level = 1)
推荐阅读
- asp.net - C# cryptoSha256 和 HashLib Sha256 的区别
- r - 更改函数中的列名
- serial-port - Chrome 应用程序 - 无法读取未定义的属性“连接”
- batch-file - 批量检查/获取 URL 中的变量
- python - 从文本文件中提取特定数据
- c++ - 通过自制软件(macOS)安装的 clang++:编译错误
- xml - Jackson XML 仅对指定标签进行反序列化
- sphinx - SphinxQL 匹配相当于 MySQL LIKE %searchterm%
- javascript - 从列表中删除项目时,Redux 分页不起作用
- ruby-on-rails - ActiveRecord::DangerousAttributeError 在测试中没有消失