Black Lives Matter. Please consider donating to Black Girls Code today.

Modifying/extending jsonEncoder for panda dataframe timespan objects

I’m hoping to use dash and plotly to visualize data stored in a pandas dataframe that includes both datetimes and Period (time spans) Time series in pandas. The Period field is not JSON Serializable using the plotly default JSON Encoder. Is there a way to extend the encoder to render periods/timespans in dash? Sorry if this is a more general plotly question answered elsewhere, but I didn’t find anything in the forums, and the code suggests that the Encoder isn’t meant to be exposed to users for modification.

Good question. In the interim, you’ll have to convert this value into a string, number, or datetime.datetime object in your own code.

I’m not sure if there is an unambiguous format for Period. Is pd.Period('2012-05', freq='D') equalivalent to 2012-05-01 or 2012-05-02? Plotting data with Period objects might require some transformation of your data into a format that has meaning on a standard linear date/time axis.

Thanks for the response. I did a little digging, and it’s possible to recast Period objects in pandas into Timestamp objects using the to_timestamp() method in Period. Once you have a Timestamp object, then plotly’s JSON Encoder will do the right thing and use the object’s isoformat() method (cf. PlotlyJSONEncoder.encode_as_datetime().

It looks like the to_timestamp() method uses the initial (start) of a Period object when building the Timestamp object, so pd.Period('2012-05', freq='D').to_timestamp() yields Timestamp('2012-05-01 00:00:00'), and PlotlyJSONEncoder().encode(pd.Period('2012-05', freq='D').to_timestamp()) returns '"2012-05-01"'.

This seems like the best workaround for now.

1 Like