2014-04-28 51 views
-2

這是我寫的一個程序。我只是想知道爲什麼我的全局變量ABSDEV_SUM在循環結束後不打印。這個變量不打印的原因是什麼?

# python_fitness_function 

import pandas as pd 
import itertools 


infile_path = "C:\\Users\\Tim\\Dropbox\\Lela.com_DrBx\\APR14_query_work\\" 

df = pd.DataFrame.from_csv(infile_path + "mp_viewed_item_AGG_affiliate_item_TOP_10.csv", sep=',', index_col=True) 


groups = df.groupby('Affiliate_ID') 


df_cameta = groups.get_group("cameta") 

cols = list(df_cameta.columns) 

while 'Affiliate_ID' in cols: 
    cols.remove('Affiliate_ID') 

Motivator_list = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] 

index = 0 
ABSDEV_SUM = 0 

for i in cols: 
    column = df[i] 
    AbsDev = sum(abs(pair[1] - pair[0]) for pair in itertools.combinations(column, 2)) 
    ABSDEV_SUM = ABSDEV_SUM + AbsDev 
    print "Motivator_" + Motivator_list[index] + "_Mean_AbsDev" 
    print AbsDev 
    index += 1 

print ABSDEV_SUM 

任何人都可以爲我闡明這一點嗎?對不起,如果它似乎是一個微不足道的步驟。

File "~\APR14_query_work\python_fitness_function.py", line 37, in <module> 
    print "Motivator_" + Motivator_list[index] + "_Mean_AbsDev" 
IndexError: list index out of range 
[Finished in 0.4s with exit code 1] 

我認爲正在發生的事情是它會通過迴路的一個附加重複,拋出了「超出範圍」的錯誤,後來乾脆不:

當循環終止我得到這個代碼打印,因爲它終止。我不知道情況是否如此,似乎是這樣,但我無法確定原因。

我試過在循環中洗牌我的行,無濟於事。

+0

您能向我們展示完整的代碼嗎? – fledgling

+0

你確定'Motivator_list'至少與'cols'一樣長嗎? –

+0

不,你在*循環結束之前得到了回溯*。 R2單位有一個不好的激勵因素。我的意思是你的'Motivator_list'沒有'cols'那麼多的成員。 – kojiro

回答

0

錯誤消息確實意味着Python終止程序,因爲它檢測到不可恢復的異常。

問題是index中的值大於Motivator_list中的元素數。

(一個典型的問題是錯過了 - 在最後一次迭代中,您創建了一個索引超過列表的末尾,也許是因爲您從1開始而不是0開始?但在這種情況下,似乎簡單地說,df_cameta.columns包含的值比Motivator_list中的12更多。也許可以使列表更長嗎?或者根據需要動態增加它?)

相關問題