5

I have the foll. dataframe:

                avi       fi_id       dates
2017-07-17  0.318844    zab_a_002  2017-07-17

When I convert it into a dictionary, I get this:

dict_avi = df.reset_index().to_dict('records')

[{'index': Timestamp('2017-07-17 00:00:00'), 'avi': 0.3188438263036763, 'fi_id': 'zab_a_002', 'dates': datetime.date(2017, 7, 17)}]

Why did the dates column become a datetime object? How can I retain it as a string?

Here are the dtypes:

avi        float64
fi_id     object
dates        object
dtype: object

2 Answers 2

12

You want to make just the datetime columns strings instead

First, make sure those columns are actually of dtype datetime

df['index'] = pd.to_datetime(df['index'])
df['dates'] = pd.to_datetime(df['dates'])

Since we went through this trouble, we could have simply turned them into strings right then

df['index'] = pd.to_datetime(df['index']).astype(str)
df['dates'] = pd.to_datetime(df['dates']).astype(str)

But this wouldn't generalize.

What I'll do instead is use select_dtypes to grab only datetime columns and convert them to strings. Then I'll update the dataframe and dump into a new dictionary. All without messing with the dataframe.

df.assign(
    **df.select_dtypes(['datetime']).astype(str).to_dict('list')
).to_dict('records')

[{'avi': 0.3188438263036763,
  'dates': '2017-07-17',
  'fi_id': 'zab_a_002',
  'index': '2017-07-17'}]
Sign up to request clarification or add additional context in comments.

1 Comment

brilliant solution !
0

On my end, I don't find the conversion to datetime mentioned by @piRSquared to be necessary. You can just do:

df[<column_name>] = df[<column_name>].astype(str)
df.to_dict('records')

Comments

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.