Nayana Madhu
Nayana Madhu

Reputation: 1225

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

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'>".

Upvotes: 1

Views: 11376

Answers (2)

jezrael
jezrael

Reputation: 863361

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

Upvotes: 1

piRSquared
piRSquared

Reputation: 294506

Consider the dataframe 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

I'm going to assume you wanted to get the 2nd element of the slice due to your passing a 2 to your function. In that case, I'm going to assume you want to use iloc and skip the preceding :.

Also, the unpacking of the *limit returns a tuple, we'll want a list.

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

Upvotes: 1

Related Questions