国产99视频精品免视看6

    1. <em id="yud1w"><acronym id="yud1w"><u id="yud1w"></u></acronym></em>
      
      
      <button id="yud1w"></button>

      python

      当前位置:首页?>?疑难杂症?>?当前文章

      疑难杂症

      iloc cannot enlarge its target object

      2021-02-19 188赞 python中国网
      每篇文章努力于解决一个问题!python高级、python面试全套、操作系统经典课等可移步文章底部。

        在使用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, in 
          series.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, in 
          df.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
      

      文章评论

      iloc cannot enlarge its target object文章写得不错,值得赞赏
      国产99视频精品免视看6