python - 类型错误 : unhashable type: 'slice'

标签 python pandas

我正在尝试使用以下数据框dfMyRoll运行回归,数据框的头部如下所示:

                SCORE  SCORE_LAG
date                           
2007-10-29 -0.031551        NaN
2007-10-30  0.000100  -0.031551
2007-10-31  0.000100   0.000100
2007-11-01  0.000100   0.000100
2007-11-02  0.000100   0.000100 

我正在使用的代码是:

import glob
import pandas as pd 
import os.path
import scipy
from scipy.stats import linregress

def main():
        
    dataPath = "C:/Users/Stacey/Documents/data/Roll"
    roll = 4
    1ID = "BBG.XNGS.AAPL.S"
    2ID = "BBG.XNGS.AMAT.S"
    print(1ID,1ID)
    cointergration = getCointergration(dataPath,1ID,2ID,roll)
    
    return

def getCointergration(dataPath,1ID,2ID,roll):
   
    for myRoll in range((roll-4),roll,1):
        path = dataPath+str(myRoll)+'/'
        filename='PairData_'+1ID+'_'+2ID+'.csv'
        
        for fname in glob.iglob(path+filename):
            
            dfMyRoll = pd.read_csv(fname, header=0, usecols=[0,31],parse_dates=[0], dayfirst=True,index_col=[0], names=['date', 'SCORE'])
            dfMyRoll['SCORE_LAG'] = dfMyRoll['SCORE'].shift(1)
            print('cointergration',dfMyRoll.head())
         
            X = dfMyRoll[1:,'SCORE']
            
            Y = dfMyRoll[1:,'SCORE_LAG']
          slope,intercept,_,_,stderr=linregress(dfMyRoll[1:,'SCORE'],dfMyRoll[1:,'SCORE_LAG'])

if __name__ == "__main__":
    
    print ("CointergrationTest...19/05/17")

    try:
        
        main()

    except KeyboardInterrupt:
        
        print ("Ctrl+C pressed. Stopping...")  

  

我收到错误:TypeError: unhashable type: 'slice'。我查看了之前关于此主题的帖子,并尝试通过以下方式将 iloc 添加到 X 和 Y 时间序列:

        X = dfMyRoll.iloc[1:,'SCORE']
        
        Y = dfMyRoll.iloc[1:,'SCORE_LAG']

但不幸的是我似乎找不到解决方案。请参阅下面的堆栈跟踪:

Traceback (most recent call last):

  File "<ipython-input-3-431422978139>", line 1, in <module>
    runfile('C:/Users/Stacey/Documents/scripts/cointergrationTest.py', wdir='C:/Users/Stacey/Documents/scripts')

  File "C:\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Stacey/Documents/scripts/cointergrationTest.py", line 64, in <module>
    main()

  File "C:/Users/Stacey/Documents/scripts/cointergrationTest.py", line 23, in main
    cointergration = getCointergration(dataPath,1ID,2ID,roll)

  File "C:/Users/Stacey/Documents/scripts/cointergrationTest.py", line 42, in getCointergration
    X = dfMyRoll[1:,'SCORE']

  File "C:\Anaconda\lib\site-packages\pandas\core\frame.py", line 2059, in __getitem__
    return self._getitem_column(key)

  File "C:\Anaconda\lib\site-packages\pandas\core\frame.py", line 2066, in _getitem_column
    return self._get_item_cache(key)

  File "C:\Anaconda\lib\site-packages\pandas\core\generic.py", line 1384, in _get_item_cache
    res = cache.get(item)

TypeError: unhashable type: 'slice'

最佳答案

您需要使用 loc 而不是 iloc:

X = dfMyRoll.loc[1:,'SCORE']

Y = dfMyRoll.loc[1:,'SCORE_LAG']

iloc 被读作“整数位置”,并且只接受整数位置。 loc 更宽容一些,并且允许两者(您也可以使用 ix)。

关于python - 类型错误 : unhashable type: 'slice' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44078930/

相关文章:

python - Tkinter 与另一个无限循环(用于语音到文本的转换)

python - 高效方式 : find row where nearly no zero appears in column

python - sys.stdout.write 对于 Windows 上的二进制文件无法正常工作

python - 在 Pelican 静态网站中托管原始 HTML 页面

pandas - 如何在 Jupyter 中打开 .tsv 文件? Jupyter.Notebook 尝试了建议,但它不起作用

pandas - 如何从数据集中搜索输入错误(日期)并根据条件替换它们?

python - 如何使用Python从AWS机器访问Github中的Excel数据

python - 无法使用 pip 安装 Pandas

python - 使用管道将数据从 c 程序发送到 python 程序?

Python - 嵌套字典,与散列元组?