在将数据帧转换为HTML时,如何更改数据帧的数据类型?

2024-03-28 14:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

因为除非我添加dtype='object',否则一个数据帧(或一个系列)的列的类型是一致的,所以我想知道在使用pandas.DataFrame.to\ html(). 例如,我希望行1-3显示为int,而行4-5显示为float。从文档到html,我知道我有一些选择,比如CSS样式。但是,我不知道如何使用函数。。你知道吗

import pandas as pd
df = pd.DataFrame({'Column1': [2, 3, 4, 5, 6.0],
'Column2': [2, 3, 3, 2, 1.0]})

这给了我一个例子:

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

因此,我想使用这个函数(对html)的方式,使我得到

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

Tags: to数据函数import类型dataframepandasdf
1条回答
网友
1楼 · 发布于 2024-03-28 14:50:03

这将起作用,尽管有点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)

基本上,您可以将所有内容转换为string,然后根据行号应用特定的格式。你知道吗

相关问题 更多 >