I have a Jupyter notebook in which I'm displaying a dataframe that I would like to:
- Hide the index
- Display a url as a clickable link
- Display a Timedelta column to the nearest day
By default the timedelta display was working, however when I try to add styling for the other two, the display for the timedelta changes to include hours/minutes/seconds.
I assume I need to specify the format for the timedelta, but I can't seem to figure out the correct way to do so. If it were a decimal field, I know I could do something like "column":"{:.2f}"
but that doesn't work with timedeltas.
Example Time!
import pandas
data = {
"count": [],
"api_id": [],
"Timedeltas": []
}
for i in range(10):
data["count"].append(i)
data["api_id"].append(f"/some_url/{i}")
data["Timedeltas"].append(pandas.Timedelta(days=i))
df = pandas.DataFrame(data)
df
By default the Timedelta column looks like I want
But if I apply formatting to get the other two pieces, I lose the timedelta formatting
def make_hyperlink(val):
# https://stackoverflow.com/a/56615369/2498161
# target _blank to open new window
return f'<a target="_blank" href="{val}">🔗</a>'
df.style.format(formatter={'api_id': make_hyperlink}).hide_index()
So my question is how do I format the timedelta, or stop the other changes from altering it's display
CodePudding user response:
This is quite an easy fix, just add a formatter for the Timedelta
column also:
df.style.format(formatter={
'api_id': make_hyperlink,
'Timedeltas': lambda v: f"{v.round('d').days} days",
}).hide()