Python TypeError:无法对 <class 'pandas.core.index.Int64Index'> 进行切片停止值索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40267116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python TypeError: Cannot do slice stop value indexing on <class 'pandas.core.index.Int64Index'>
提问by Abhishek Jaiswal
Am getting a Type Error, while trying to filter some past data using python and pandas. Here's the error
在尝试使用 python 和 pandas 过滤一些过去的数据时遇到类型错误。这是错误
TypeError: cannot do slice stop value indexing on < class 'pandas.core.index.Int64Index'> with these indexers [327.0] of < type 'float'>
类型错误:无法使用 < type 'float'> 的这些索引器 [327.0] 对 < class 'pandas.core.index.Int64Index'> 进行切片停止值索引
Code
代码
# 65% of training data
ratio = 0.65
train_data_df = df_replace[:round(dataset_length*ratio)]
test_data_df = df_replace[-(1-round(dataset_length*ratio)):]
# Create Respected CSV
train_data_df.to_csv('Train.csv',index=False)
test_data_df.to_csv('Test.csv',index=False)
Additional Info
附加信息
The code is working upto creating a new CSV file India_in_Tests_Filter.csv
that has more than 450 rows and 3 columns as follows:
该代码正在创建一个新的 CSV 文件India_in_Tests_Filter.csv
,该文件具有 450 多行和 3 列,如下所示:
Result Toss Bat
Lost won 1st
Won won 2nd
While India_in_Tests.csv
have more than 450 rows and 7 columns.
虽然India_in_Tests.csv
有超过 450 行和 7 列。
So folks, any thoughts on that?
所以各位,有什么想法吗?
回答by piRSquared
consider df
考虑 df
df = pd.DataFrame(range(10), list(range(320, 330)))
then slice it with
然后用它切片
df[:327.0]
TypeError: cannot do slice indexing on <class 'pandas.indexes.numeric.Int64Index'> with these indexers [327.0] of <type 'float'>
TypeError: cannot do slice indexing on <class 'pandas.indexes.numeric.Int64Index'> with these indexers [327.0] of <type 'float'>
your round
function is returning a float
. Make it an int
instead
您的round
函数正在返回一个float
. 使它成为int
替代
df[:int(327.0)]
what your code should look like
你的代码应该是什么样子
train_data_df = df_replace[:int(dataset_length*ratio)]
test_data_df = df_replace[-(1-int(dataset_length*ratio)):]