Python TypeError:无法对<class'pandas.core.index.Int64Index'>

2024-04-29 12:55:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试使用python和pandas筛选一些过去的数据时遇到类型错误。这里有个错误

TypeError: cannot do slice stop value indexing on < class 'pandas.core.index.Int64Index'> with these indexers [327.0] of < type 'float'>

代码

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

附加信息

代码将一直工作到创建一个新的CSV文件India_in_Tests_Filter.csv,该文件包含450多行和3列,如下所示:

Result Toss Bat

Lost   won  1st 
Won    won  2nd

India_in_Tests.csv有450多行7列。

各位,有什么想法吗?


Tags: ofcsv代码testpandasdfdataindex
1条回答
网友
1楼 · 发布于 2024-04-29 12:55:05

考虑df

df = pd.DataFrame(range(10), list(range(320, 330)))

然后用切片

df[:327.0]
TypeError: cannot do slice indexing on <class 'pandas.indexes.numeric.Int64Index'>
with these indexers [327.0] of <type 'float'>

您的round函数返回一个float。改为int

df[:int(327.0)]

enter image description here

您的代码应该是什么样的

train_data_df = df_replace[:int(dataset_length*ratio)]  
test_data_df = df_replace[-(1-int(dataset_length*ratio)):]  

相关问题 更多 >