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

Nayana Madhu picture Nayana Madhu · Mar 15, 2017 · Viewed 9.9k times · Source

I've a user defined function as follows:-

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))  

please refer thisimage

when I use the function as

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

I'm getting an error as

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

Answer

jezrael picture jezrael · Mar 15, 2017

I think you need remove * from *limit if argument limit is integer and rank_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)

With borrowing sample with another answer it works perfectly:

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

EDIT:

I think you need add dataframe as argument too:

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