Python 这些数据相加为特定的列值

Python 这些数据相加为特定的列值,python,pandas,dataframe,typeerror,Python,Pandas,Dataframe,Typeerror,这段小小的代码给我带来了太多的麻烦。如果可以的话,我将非常感谢您的帮助。提前谢谢你帮我看一下这个 我试图从前面的22个数据点总结价格和数量,我添加了一个名为dtt的列来保存这个值我在这里试图表示的公式是: vamp = [sum(1, dtt) price * volume] / [sum(1,dtt) volume] 这是我的密码 # Import necessary libraries import numpy as np import pandas as pd import os #

这段小小的代码给我带来了太多的麻烦。如果可以的话,我将非常感谢您的帮助。提前谢谢你帮我看一下这个

我试图从前面的22个数据点总结价格和数量,我添加了一个名为dtt的列来保存这个值
我在这里试图表示的公式是:

vamp = [sum(1, dtt) price * volume] / [sum(1,dtt) volume]
这是我的密码

# Import necessary libraries
import numpy as np
import pandas as pd
import os

# Load SPY dataset
spy_data = pd.read_csv('SPY.csv', parse_dates=['Date'])
# Compute Daily Return
spy_data['daily_ret'] = (spy_data['Adj Close'] - (spy_data['Adj Close']).shift(1)) / ((spy_data['Adj Close']).shift(1)) * 100
spy_data['daily_ret'] = spy_data['daily_ret'].fillna(0.0)

# calculate Annualized Volatility
rsquare = (spy_data['daily_ret']) ** 2
spy_data['annualized_volatility']=(np.sqrt(rsquare.rolling(252).sum() / 251) * np.sqrt(252))
spy_data['annualized_volatility'] = spy_data['annualized_volatility'].fillna(0)

spy_shares = 889112600

# Calculate Days to Trade
spy_data['dtt'] = spy_shares / (spy_data['Volume'].rolling(22).sum()/22)
spy_data['dtt'] = spy_data['dtt'].fillna(1).astype(int)

# Calculate VWAP
#numerator is equal to the sum of the price * volume of the latest DTT
numerator = spy_data.loc[0:spy_data['dtt'], 'Adj Close'].sum()#*spy_data.loc[0:spy_data['dtt'], 'Volume']
#denominator = spy_data.loc[0:spy_data['dtt'], 'Volume']
#spy_data['vwap'] = numerator / denominator
print(spy_data)
我注释掉了其他行,因为我试图一步一步地解决这个问题。我需要的价格栏是
Adj Close

无论我在切片方面做了什么尝试,我总是会出错。这是当前的一个:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-ade975138e12> in <module>
      7 # Calculate VWAP
      8 #numerator is equal to the sum of the price * volume of the latest DTT
----> 9 numerator = spy_data.loc[0:spy_data['dtt']].sum()#*spy_data[0:spy_data['dtt'], 'volume']
     10 #denominator = spy_data.loc[0:spy_data['dtt'], 'Volume']
     11 #spy_data['vwap'] = numerator / denominator

~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in __getitem__(self, key)
   1408 
   1409             maybe_callable = com.apply_if_callable(key, self.obj)
-> 1410             return self._getitem_axis(maybe_callable, axis=axis)
   1411 
   1412     def _is_scalar_access(self, key: Tuple):

~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in _getitem_axis(self, key, axis)
   1770         if isinstance(key, slice):
   1771             self._validate_key(key, axis)
-> 1772             return self._get_slice_axis(key, axis=axis)
   1773         elif com.is_bool_indexer(key):
   1774             return self._getbool_axis(key, axis=axis)

~/.local/lib/python3.6/site-packages/pandas/core/indexing.py in _get_slice_axis(self, slice_obj, axis)
   1438         labels = obj._get_axis(axis)
   1439         indexer = labels.slice_indexer(
-> 1440             slice_obj.start, slice_obj.stop, slice_obj.step, kind=self.name
   1441         )
   1442 

~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in slice_indexer(self, start, end, step, kind)
   5025         slice(1, 3)
   5026         """
-> 5027         start_slice, end_slice = self.slice_locs(start, end, step=step, kind=kind)
   5028 
   5029         # return a slice

~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in slice_locs(self, start, end, step, kind)
  5245         end_slice = None
  5246         if end is not None:
   -> 5247             end_slice = self.get_slice_bound(end, "right", kind)
  5248         if end_slice is None:
  5249             end_slice = len(self)

~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_slice_bound(self, label, side, kind)
  5155         # we need to look up the label
  5156         try:
   -> 5157             slc = self.get_loc(label)
  5158         except KeyError as err:
  5159             try:

~/.local/lib/python3.6/site-packages/pandas/core/indexes/range.py in get_loc(self, key, method, tolerance)
   377             except ValueError:
   378                 raise KeyError(key)
   --> 379         return super().get_loc(key, method=method, tolerance=tolerance)
   380 
   381     @Appender(_index_shared_docs["get_indexer"])

~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
  2888                 )
  2889             try:
   -> 2890                 return self._engine.get_loc(key)
  2891             except KeyError:
  2892                 return self._engine.get_loc(self._maybe_cast_indexer(key))

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

TypeError: '0        1
 1        1
 2        1
 3        1
 4        1
    ..
 4694     9
 4695     9
 4696    10
 4697    10
 4698    11
 Name: dtt, Length: 4699, dtype: int64' is an invalid key
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
7#计算VWAP
8#分子等于最新DTT的价格*数量之和
---->9分子=spy_数据.loc[0:spy_数据['dtt']].sum()#*spy_数据[0:spy_数据['dtt'],卷]
10#分母=spy#u data.loc[0:spy#u data['dtt'],'Volume']
11#间谍数据['vwap']=分子/分母
~/.local/lib/python3.6/site-packages/pandas/core/index.py in\uuuu getitem\uuuu(self,key)
1408
1409 maybe_callable=com.apply_if_callable(key,self.obj)
->1410返回自我。获取项目轴(可能可调用,轴=轴)
1411
1412定义是标量访问(self,key:Tuple):
轴中的~/.local/lib/python3.6/site-packages/pandas/core/index.py(self、key、axis)
1770如果isinstance(键,切片):
1771自我验证键(键,轴)
->1772返回自我。获取切片轴(键,轴=轴)
1773 elif com.is_bool_索引器(键):
1774返回自我轴(键,轴=轴)
轴中的~/.local/lib/python3.6/site-packages/pandas/core/index.py(self、slice、obj、axis)
1438标签=对象获取轴(轴)
1439索引器=labels.slice\u索引器(
->1440 slice_obj.start、slice_obj.stop、slice_obj.step、kind=self.name
1441         )
1442
切片索引器中的~/.local/lib/python3.6/site-packages/pandas/core/index/base.py(self、start、end、step、kind)
5025片(1,3)
5026         """
->5027开始\u片,结束\u片=自身。片\u位置(开始,结束,步骤=步骤,种类=种类)
5028
5029#返回一个切片
切片中的~/.local/lib/python3.6/site-packages/pandas/core/index/base.py(self、start、end、step、kind)
5245端片=无
5246如果结束不是无:
->5247 end\u slice=self.get\u slice\u bound(end,“right”,kind)
5248如果end_切片为无:
5249端片=透镜(自身)
获取切片绑定中的~/.local/lib/python3.6/site-packages/pandas/core/index/base.py(self、label、side、kind)
我们需要查一下标签
5156尝试:
->5157 slc=自我获取位置(标签)
5158除KeyError as err外:
5159尝试:
get_loc中的~/.local/lib/python3.6/site-packages/pandas/core/index/range.py(self、key、method、tolerance)
377除值错误外:
378升起钥匙错误(钥匙)
-->379 return super().get_loc(键,方法=方法,公差=公差)
380
381@Appender(_index_shared_docs[“get_indexer”])
get_loc中的~/.local/lib/python3.6/site-packages/pandas/core/index/base.py(self、key、method、tolerance)
2888                 )
2889尝试:
->2890自动返回发动机。获取锁定位置(钥匙)
2891键错误除外:
2892返回self.\u引擎。获取self.\u loc(self.\u可能\u cast\u索引器(键))
pandas/_libs/index.pyx在pandas中。_libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx在pandas中。_libs.index.IndexEngine.get_loc()
TypeError:“0 1”
1        1
2        1
3        1
4        1
..
4694     9
4695     9
4696    10
4697    10
4698    11
名称:dtt,长度:4699,dtype:int64'是无效密钥

您提供的代码不可运行。您所说的
0:spy_data['dtt']]的loc是什么意思?
公式是将最新的dtt值相加,因此我认为需要从dtt列中选择该值。因此,对于第一次计算,它将从0到spy_data['dtt']中找到的dtt。