您的位置: 网站首页> 大家问> 当前文章
iloc cannot enlarge its target object
老董2021-02-19186围观,123赞
在使用pandas过程中,你可能遇见iloc cannot enlarge its target object这个问题,这个错误提示你df或者series的索引超出了范围,要解决该问题其实很简单。
我们先复现一下这个问题:
1、试图给1个series新增元素赋值。
# -*- coding:UTF-8 -*- import pandas as pd series = pd.Series([1,2,3]) series.iloc[3] = 4 print(series)
Traceback (most recent call last): File "D:/py3script/pandas_xuexi/pandas_test.py", line 5, inseries.iloc[3] = 4 File "D:\python3\install\lib\site-packages\pandas\core\indexing.py", line 667, in __setitem__ self._has_valid_setitem_indexer(key) File "D:\python3\install\lib\site-packages\pandas\core\indexing.py", line 1394, in _has_valid_setitem_indexer raise IndexError("iloc cannot enlarge its target object") IndexError: iloc cannot enlarge its target object
2、试图给1个df新增1行赋值。
# -*- coding:UTF-8 -*- import pandas as pd df = pd.DataFrame([[1, 2], [4, 5], [7, 8]], index=['x', 'y', 'z'], columns=['max_speed', 'shield']) df.iloc[3] = 4 print(df)
Traceback (most recent call last): File "D:/py3script/pandas_xuexi/pandas_test.py", line 8, indf.iloc[3] = 4 File "D:\python3\install\lib\site-packages\pandas\core\indexing.py", line 667, in __setitem__ self._has_valid_setitem_indexer(key) File "D:\python3\install\lib\site-packages\pandas\core\indexing.py", line 1394, in _has_valid_setitem_indexer raise IndexError("iloc cannot enlarge its target object") IndexError: iloc cannot enlarge its target object
如果series或者df中以新增元素的方式赋值,那么应该使用loc来实现。代码如下:
# -*- coding:UTF-8 -*- import pandas as pd df = pd.DataFrame([[1, 2], [4, 5], [7, 8]], index=['x', 'y', 'z'], columns=['max_speed', 'shield']) df.loc[4] = 4 print(df)
max_speed shield x 1 2 y 4 5 z 7 8 4 4 4
很赞哦!
python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群
文章评论
-
iloc cannot enlarge its target object文章写得不错,值得赞赏