1

I am using Pandas in Python 3,

I have a dataframe whose index is like '20160727', but the datatype is 'object'.

I am trying to convert it into string type.

I tried:

data.index.astye(str, copy=False)

and data.index = data.index.map(str)

But even after these two operations,

I get:

data.index.dtype is dtype('O')

I want to use sort after converting the index to string. How can I convert the index to string datatype so that I can process it like a string?

Rafael
  • 651
  • 13
  • 30

1 Answers1

3

In pandas, object is type string.

dtype('O') means it is a python type object. You can see more info about this here

As an example of what you want to achieve:

data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=[20160103, 20160102, 20160104, 20160101])
df.index =  pd.to_datetime(df.index, format='%Y%m%d')
df.sort_index()
Merelda
  • 1,318
  • 2
  • 12
  • 26