-1

Suppose I have the following example:

import pandas as pd

In [11]: df = pd.DataFrame(data=[0.0], index=pd.TimedeltaIndex([250], unit='d'))

In [12]: df.to_json(orient='split', date_format='iso')
Out[12]: '{"columns":[0],"index":["1970-09-08T00:00:00.000Z"],"data":[[0.0]]}'

In [13]: 

As you can see I want to convert a pandas data frame to a json format. Unfortunately, I can't find a way how to transform the index also to the desired output. In this case the index should be 250 days. This is what I see if I print the df in python:

df
Out[13]: 
            0
250 days  0.0

In [14]: 

Is there a way to achieve this, i.e. so that I could rebuild the data frame getting the correct index.

math
  • 1,868
  • 4
  • 26
  • 60

1 Answers1

-1

You can add a column like ['days'] to the dataframe:

df['days'] = df.index.days

and then the df.to_json() will just have a key called "days" with the number of days.

Alternatively, if you want the index to say "250 days", just coerce to str:

df.index = df.index.astype(str)

And the result of df.to_json(orient='split', date_format='iso') will be:

'{"columns":[0,"days"],"index":["250 days"],"data":[[0.0,250]]}'
wkzhu
  • 1,616
  • 13
  • 23