gpt4 book ai didi

python - <类 'pandas.indexes.numeric.Int64Index'> 的类型错误 : cannot do slice indexing on with these indexers [(2, )]

转载 作者:行者123 更新时间:2023-12-01 03:12:03 28 4
gpt4 key购买 nike

我有一个用户定义的函数,如下所示:-

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

最佳答案

考虑数据框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

关于python - <类 'pandas.indexes.numeric.Int64Index'> 的类型错误 : cannot do slice indexing on <class 'tuple' > with these indexers [(2, )],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42804573/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com