Abhishek Jaiswal Abhishek Jaiswal - 1 month ago 14
Python Question

Python TypeError: Cannot do slice stop value indexing on <class 'pandas.core.index.Int64Index'>

Am getting a Type Error, while trying to filter some past data using python and pandas. Here's the error


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


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:

Result Toss Bat

Lost won 1st
Won won 2nd


While
India_in_Tests.csv
have more than 450 rows and 7 columns.

So folks, any thoughts on that?

Answer

consider 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'>

your round function is returning a float. Make it an int instead

df[:int(327.0)]

enter image description here

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)):]  
Comments