TypeError:不能对<class'pandas.indexes.numeric.int64index'=“”>使用<class'tuple'=“”>的这些索引器[(2,)]进行切片索引

时间:2017-03-15 08:32:08

标签: python python-3.x pandas slice argument-unpacking

我用户定义的功能如下: -

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

2 个答案:

答案 0 :(得分:1)

如果参数**limitlimit,我认为您需要从integer删除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)

借用另一个答案的借用样本,它可以完美地运作:

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

答案 1 :(得分: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