0

Running

for index, row in df.iterrows():
    print(df.iloc[index,0])

yields the following error:

ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

Index is 0:

index
Out[57]: '0'

But somehow, my index consists of strings which I can confirm via

type(index)
Out[63]: str

This is although I've applied df.reset_index().

How can I ensure that the index of my df (df.index) consists of integers?

EDIT:

df.index
Out[69]: 
Index(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
       ...
       '14829', '14830', '14831', '14832', '14833', '14834', '14835', '14836',
       '14837', '14838'],
      dtype='object', length=14839)
0

2 Answers 2

2
In [85]: df.index
Out[85]: Index(['0', '1', '2', '3', '4', '5', '6'], dtype='object')

In [86]: df.index = df.index.astype(int)

In [87]: df.index
Out[87]: Int64Index([0, 1, 2, 3, 4, 5, 6], dtype='int64')

Make use of astype

Sign up to request clarification or add additional context in comments.

Comments

0

index results in '0' which means it is a string. You can easily make it an integer by using int() function.

At your case, int(index) will solve the problem.

3 Comments

Thank you for your answer. This will not change the entire df.index() to ints.
I've updated my question to make my request more clear.
Well, you make try to use df[column_name] = df[column_name].astype(int) after creating the DataFrame.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.