我有一个,它在html中如下所示:
df = pd.DataFrame([
[54, 21, 30, 12, '20-01-2002'],
[52, 26, 31, 2, '22-01-2002'],
[50, 16, 11, 15, '223-01-2002']
], columns=['A', 'B', 'C', 'D', 'date']).transpose()
当将dataframe呈现为HTML时,我需要在第一列上显示一个趋势图标(向上或向下箭头),将其与第二列中的值进行比较,这样最后的html呈现如下所示:
首先,我认为这就像在dataframe中添加带有箭头的span标记一样简单。
<span style="color:green;">▲</span> <!-- For Up Arrow -- >
<span style="color:green;">▼</span> <!-- For Down Arrow -- >
所以我试着把它添加到数据文件中
df['A'] = df['A'].astype('str') + <span style="color:green;">▲</span>
但是,当将span标记表示为html时,斯泰勒试图转义span标记,并将其显示为文本。我试过同时使用escape=''html
和escape='latex'
lated为span标记工作,但仍然转义& with &
我不太熟悉斯泰勒的工作原理,所以需要帮助。
发布于 2022-09-16 13:07:44
对于笔记本中的交互式显示,您可以使用:
import numpy as np
UP = '<span style="color:green;">▲</span>'
DOWN = '<span style="color:red;">▼</span>'
# make copy to leave original dataframe unchanged
df2 = df.copy()
# select only relevant rows
idx = df.index!='date'
# convert to string and add arrow
df2.loc[idx, 0] = (df.loc[idx, 0].astype(str)
+ np.where(df.loc[idx, 0].gt(df.loc[idx, 1]), UP, DOWN)
)
df2.style
对于HTML,请使用escape=None
df2.to_html(escape=None)
在平等问题上没有任何好处:
df2.loc[idx, 0] = (df.loc[idx, 0].astype(str)
+np.sign(np.sign(df.loc[idx, 0].sub(df.loc[idx, 1]))
).map({1:UP, -1:DOWN, 0:''})
)
df2.style
使用CSS
基于@mplungjan的回答,这里提供了一种使用带有style.set_td_classes
的styler的HTML/CSS功能的替代方法。
注意:我在这里格式化了更多的单元格(相对于下一列):
CSS = '''
<style>
.up::after {
content: "▲";
color: green;
}
.down::after {
content: "▼";
color: red;
}
</style>
'''
def arrow_up_down(df):
return (np.sign(df.apply(pd.to_numeric, errors='coerce')
.diff(-1, axis=1))
.replace({1:'up', -1:'down', 0: np.nan})
)
from IPython.display import HTML
HTML(CSS+df.style.set_td_classes(arrow_up_down(df)).to_html())
产出:
发布于 2022-09-16 13:10:56
添加两个具有伪选择器的类。
https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Table-styles
.up::after {
content: "▲";
color: green;
}
.down::after {
content: "▼";
color: red;
}
<table border="1" class="dataframe mystyle">
<thead>
<tr style="text-align: center;">
<th></th>
<th>date</th>
<th>analysis_tool</th>
<th>num1</th>
<th>database</th>
<th>num2</th>
<th>os</th>
<th>num3</th>
<th>bool</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>2018-04-21</td>
<td>pandas</td>
<td>153.474246</td>
<td>mysql</td>
<td class="up">0.658533</td>
<td>ios</td>
<td class="down">74</td>
<td>True</td>
</tr>
</tbody>
</table>
https://stackoverflow.com/questions/73745198
复制相似问题