2017-03-15 237 views
0

我有一個用戶定義的函數,如下所示: -TypeError:無法對<class'pandas.indexes.numeric.Int64Index'>使用<class'元組''的這些索引器[(2,)]進行分片索引>

def genre(option,option_type,*limit): 
    option_based = rank_data.loc[rank_data[option] == option_type] 
    top_option_based = option_based[:limit] 
    print(top_option_based) 
    top_option_based.to_csv('top_option_based.csv') 
    return(top_option_based)) 

請參閱本image

,當我使用的

genre('genre','Crime',2) 

我得到一個錯誤

功能
TypeError: cannot do slice indexing on <class 'pandas.indexes.numeric.Int64Index'> with these indexers [(2,)] of <class 'tuple'>". 
+0

看來你需要刪除'*' - '流派(選項,option_type,極限)' – jezrael

+1

您也可以在返回行額外的右括號,可能是一個錯字。我會補充說,作爲功能的代表,沒有人可以運行或定義它,因爲缺少使其起作用的項目,例如rank_data不存在。嘗試使問題完全解決,否則如果片段中有太多未知數,則解決起來可能會很困難。 – grail

+0

但是當我在另一個文件中導入這個函數時,我得到一個錯誤,因爲''genre()需要2個位置參數,但是3個被賦予了''。爲了避免這個錯誤,我用* –

回答

1

我認爲你需要從*limit刪除*如果參數limitintegerrank_data

def genre(option,option_type,limit): 
    option_based = rank_data.loc[rank_data[option] == option_type] 
    top_option_based = option_based[:limit] 
    print(top_option_based) 
    top_option_based.to_csv('top_option_based.csv') 
    return(top_option_based) 

與另一個答案借貸樣本它完美的作品:

def genre(option,option_type,limit): 
    option_based = rank_data.loc[rank_data[option] == option_type] 
    top_option_based = option_based[:limit] 
    print(top_option_based) 
    top_option_based.to_csv('top_option_based.csv') 
    return(top_option_based) 

print (genre('genre', 'Crime', 2)) 
    genre 
0 Crime 
1 Crime 

編輯:

我認爲你需要添加dataframe作爲參數○:

def genre(rank_data, option,option_type,limit): 
    option_based = rank_data.loc[rank_data[option] == option_type] 
    top_option_based = option_based[:limit] 
    print(top_option_based) 
    top_option_based.to_csv('top_option_based.csv') 
    return(top_option_based) 

print (genre(rank_data, 'genre', 'Crime', 2)) 
    genre 
0 Crime 
1 Crime 
+0

確定插入了我的rank_data的圖像,但是當我在另一個文件中導入此函數時,出現'genre()需要2個位置參數,但3個被賦予「'。爲了避免這個錯誤,我使用了* –

+0

然後檢查另一個答案。 – jezrael

+0

看來你需要添加參數 - 數據框。 – jezrael

1

考慮數據框rank_data

rank_data = pd.DataFrame(dict(
     genre=['Crime'] * 4 + ['Romance'] * 4 
    )) 

print(rank_data) 

    genre 
0 Crime 
1 Crime 
2 Crime 
3 Crime 
4 Romance 
5 Romance 
6 Romance 
7 Romance 

我會假設你想獲得切片的第二個元素由於你傳遞一個2給你的函數。在這種情況下,我假設您想使用iloc並跳過前面的:

此外,*limit的解包返回一個元組,我們需要一個列表。

def genre(option,option_type,*limit): 
    option_based = rank_data.loc[rank_data[option] == option_type] 
    top_option_based = option_based.iloc[list(limit)] 
       # I changed this bit ^^^^^^^^^^^^^^^^^ 
    top_option_based.to_csv('top_option_based.csv') 
    return(top_option_based) 

genre('genre', 'Crime', 2) 

    genre 
2 Crime 

genre('genre', 'Crime', 2, 3) 

    genre 
2 Crime 
3 Crime 
+0

我不需要第二個元素。我需要元素達到2(限制) –

相關問題