以下代码计算数据框中收盘价所有值的指标值(例如SMA):
import pandas_ta as pta
df['SMA']= pta.sma(close=df['Close_NAVI.O'], length=10)
我的问题是,有没有一种方法可以说,为附加到数据帧的新结束值计算SMA的值
我知道我们可以重新运行df['SMA']= pta.sma(close=df['Close_NAVI.O'], length=10)
以获得所有收盘价的SMA值,但假设我有一个运行到数千行的大数据框,我不想浪费我的计算资源来继续重新计算所有行的值
为了让您对我上面所说的有一个形象的了解,让我们假设我现在在下面数据框的“2014-05-07 00:00:00”上有一个新的收盘价“16.6000”,我只想计算该特定收盘价的SMA值
我尝试使用下面的代码
df.loc[14, 'SMA']= pta.sma(close=df['Close_NAVI.O'], length=10)
但我得到了以下错误:
df.loc[14, 'SMA']= pta.sma(close=df['Close_NAVI.O'], length=10)
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3325, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-64-3b6dc5d213d8>", line 1, in <module>
df.loc[14, 'SMA']= pta.sma(close=df['Close_NAVI.O'], length=10)
File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 670, in __setitem__
iloc._setitem_with_indexer(indexer, value)
File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 1642, in _setitem_with_indexer
value = self._align_series(indexer, value)
File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 1952, in _align_series
raise ValueError("Incompatible indexer with Series")
ValueError: Incompatible indexer with Series
df.loc[13, 'SMA']= pta.sma(close=df['Close_NAVI.O'], length=10)
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3325, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-65-f0f4255ec13c>", line 1, in <module>
df.loc[13, 'SMA']= pta.sma(close=df['Close_NAVI.O'], length=10)
File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 670, in __setitem__
iloc._setitem_with_indexer(indexer, value)
File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 1642, in _setitem_with_indexer
value = self._align_series(indexer, value)
File "C:\Python37\lib\site-packages\pandas\core\indexing.py", line 1952, in _align_series
raise ValueError("Incompatible indexer with Series")
ValueError: Incompatible indexer with Series
有人能建议一种方法吗
尝试对数据帧进行子集设置,将结果复制到新的数据帧中(确保使用df_subset.copy()以不更改原始df),执行计算,然后检索最后一个值并将其插入原始数据帧中
这样,您的新计算将始终在一个固定大小的数据帧上执行,该数据帧的大小取决于它需要的大小。我相信还有更优雅的解决方案,但这将完成工作
相关问题 更多 >
编程相关推荐