Reputation: 1323
After styling my pandas DataFrame
in Python
. I noticed the index started at 0
. How do I make it start at 1
.
I tried to do df.index = np.arange(1, len(df))
but it gives me an error: ValueError: Length mismatch: Expected axis has 1119 elements, new values have 1118 elements
Here is my code for your review:
from IPython.display import HTML
df.index = np.arange(1, len(df))
def hover(hover_color="#FF5733"):
return dict(selector="tbody tr:hover",
props=[("background-color", "%s" % hover_color)])
styles = [
#table properties
dict(selector=" ",
props=[("margin","0"),
("font-family",'calibri'),
("border-collapse", "collapse"),
("border","none"),
("border", "2px solid #ccf")
]),
#header color - optional
dict(selector="thead",
props=[("background-color","#489AF3")
]),
#background shading
dict(selector="tbody tr:nth-child(even)",
props=[("background-color", "#fff")]),
dict(selector="tbody tr:nth-child(odd)",
props=[("background-color", "#eee")]),
#cell spacing
dict(selector="td",
props=[("padding", ".5em")]),
#header cell properties
dict(selector="th",
props=[("font-size", "130%"),
("text-align", "center")]),
#caption placement
dict(selector="caption",
props=[("caption-side", "bottom")]),
#render hover last to override background-color
hover()
]
# this forces grey background on header
styler = df.style.set_properties(**{'text-align': 'center'}).set_table_styles(styles)
# HTML string
html = styler.render()
# save html
with open('file2.html', 'w') as f:
f.write(html)
Upvotes: 2
Views: 2618
Reputation: 865
As mentioned in the comments df.index = np.arange(1, len(df)+1)
does the trick
Upvotes: 5