代码之家  ›  专栏  ›  技术社区  ›  atkayla

使用[-1]获取列的最后一行?

  •  1
  • atkayla  · 技术社区  · 6 年前

    我有这样的地方代码,各地似乎工作良好。

    df['FAST_MA'] = df['close'].rolling(5).mean()
    lfma = df['FAST_MA'][-1]
    

      ERROR - error from callback <function on_message at 0x12619cc20>: -1.0
      File "/usr/local/lib/python3.7/site-packages/websocket/_app.py", line 346, in _callback
        callback(self, *args)
      File "file.py", line 177, in calculate
        lfma = df['FAST_MA'][-1]
      File "/usr/local/lib/python3.7/site-packages/pandas/core/series.py", line 868, in __getitem__
        result = self.index.get_value(self, key)
      File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/numeric.py", line 375, in get_value
        loc = self.get_loc(k)
      File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/numeric.py", line 436, in get_loc
        tolerance=tolerance)
      File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2659, in get_loc
        return self._engine.get_loc(self._maybe_cast_indexer(key))
      File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
      File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
      File "pandas/_libs/hashtable_class_helper.pxi", line 382, in pandas._libs.hashtable.Float64HashTable.get_item
      File "pandas/_libs/hashtable_class_helper.pxi", line 388, in pandas._libs.hashtable.Float64HashTable.get_item
    

    然后我就不得不做这样的事了。

    # df['FAST_MA'] = df['close'].rolling(5).mean()
    lfma = df['FAST_MA'].iloc[-1]
    

    df['FAST_MA'][-1] 突入意外情况?

    1 回复  |  直到 6 年前
        1
  •  1
  •   jezrael    6 年前

    我尝试类似的问题,选择 DatetimeIndex 两方面都很好:

    df = pd.DataFrame({
        'close': list(range(4))}, index=pd.date_range('2019-10-01', periods=4))
    print (df)
    
    df['FAST_MA'] = df['close'].rolling(2).mean()
    print (df)
                close  FAST_MA
    2019-10-01      0      NaN
    2019-10-02      1      0.5
    2019-10-03      2      1.5
    2019-10-04      3      2.5
    
    print (df['FAST_MA'][-1])
    2.5
    print (df['FAST_MA'].iloc[-1])
    2.5
    

    RangeIndex :

    d = {'close': [1, 2, 3], 'col2': [3, 4, 5]}
    df=pd.DataFrame(data=d)
    
    df['FAST_MA'] = df['close'].rolling(2).mean()
    print (df)
    
    print (df['FAST_MA'].iloc[-1])
       close  col2  FAST_MA
    0      1     3      NaN
    1      2     4      1.5
    2      3     5      2.5
    
    print (df['FAST_MA'][-1])
    KeyError: -1
    

    此错误意味着熊猫正在查找索引值 -1 而是最后一个职位,因为不存在而加薪 KeyError .

    最普遍的解决方法是使用方法 Series.iloc Series.iat

    如果需要,也可以选择 DataFrame DataFrame.iat DataFrame.iloc :

    df.iat[-1, df.columns.get_loc('FAST_MA')]
    df.iloc[-1, df.columns.get_loc('FAST_MA')]
    
        2
  •  0
  •   Gowrav Tata    6 年前

    数据帧['feature_name'].iloc[-1]

    不使用iloc访问最后一个元素是不适用的,即使用负索引时