Reputation: 410
Since the columns of a pandas DataFrame (or a Series) are homogeneously of type unless I add dtype='object', I wondered how could I change the dtype of certain rows when using pandas.DataFrame.to_html(). For example I would like that the rows 1-3 are displayed as int, whereas the rows 4-5 should be displayed as floats. From the docs of to_html I understand that I have some options like CSS styles. However, I don't know how to do it with the function..
import pandas as pd
df = pd.DataFrame({'Column1': [2, 3, 4, 5, 6.0],
'Column2': [2, 3, 3, 2, 1.0]})
This gives me for example:
Column1 Column2
0 2.0 2.0
1 3.0 3.0
2 4.0 3.0
3 5.0 2.0
4 6.0 1.0
So I want to use this function (to_html) in a way so that I get
df_html = df.to_html(*options*)
from IPython.display import HTML
HTML(df_html)
Column1 Column2
0 2 2
1 3 3
2 4 3
3 5.0 2.0
4 6.0 1.0
Upvotes: 0
Views: 325
Reputation: 5879
This will work, even though it's a bit ad-hoc
:
df = df.astype(str)
sty = lambda x : str(int(float(x)))
for col in df.columns:
df.loc[df.index<3, col] = df.loc[df.index<3, col].apply(sty)
Basically, you convert everything to string
and then apply specific formatting depending on the row number.
Upvotes: 1