【问题标题】:Python show HTML arrows to dataframePython向数据框显示HTML箭头
【发布时间】:2019-02-14 06:06:13
【问题描述】:

我创建了一个数据框 df,

           Value     Change        Direction    
Date                                    
2015-03-02  2117.38   NaN              0        
2015-03-03  2107.79  -9.609864         0    
2015-03-04  2098.59  -9.250000         0    
2015-03-05  2101.04   2.510010         1    
2015-03-06  2071.26  -29.780029        0
. 
.
.

现在我试图用向下箭头替换方向值 0,用向上箭头替换 1。向下箭头的 HTML 代码是 ಓ

【问题讨论】:

  • 你应该使用一个简单的地图,像这样:df['Direction'] = df['Direction'].map({0:'&#3219', 1: 'codeforup'})。现在,如果这在您的 UI 中显示箭头,那我不知道。
  • 感谢@AntonvBR 的回复,但它显示字符串 'ಓ' 而不是箭头
  • 不要使用 Html 代码。只需复制符号并使用它。从这里复制:- usefulshortcuts.com/alt-codes/bullet-alt-codes.php

标签: python html pandas dataframe replace


【解决方案1】:

使用

df['direction'] = df['direction'].map({0: '↓', 1: '↑'})

import pandas as pd

Title = ('jimmy', 'red', 'blue', 'brad', 'oranges')
value = (82, 38 , 55, 19, 33)
direction = (0, 1, 1, 0, 0)

df = pd.DataFrame({'Title': Title, 'value': value,'direction':direction})
df['direction'] = df['direction'].map({0: '↓', 1: '↑'})
df

输出

    Title   value   direction
0   jimmy   82      ↓
1   red     38      ↑
2   blue    55      ↑
3   brad    19      ↓
4   oranges 33      ↓

【讨论】:

    【解决方案2】:

    试试下面的代码示例:

    import pandas as pd
    
    Fruits = ('Apple', 'Mango', 'Grapes', 'Banana', 'orange')
    Price = (100, 80, 50, 90, 60)
    direction = (1, 0, 1, 1, 0)
    
    df = pd.DataFrame({'Fruits': Fruits, 'Price': Price,'direction':direction})
    
    df.direction.replace([1, 0],["↑", "↓"], inplace=True)    #replace the values using html codes for up and down arrow.
    
    html_df= df.to_html()    #convert the df to html for better formatting view
    
    html_df = html_df.replace("<td>&amp;#8595;</td>","<td><font color = red>&#8595;</font></td>")    # Remove extra tags and added red colour to down arrow
    html_df = html_df.replace("<td>&amp;#8593;</td>","<td><font color = green>&#8593;</font></td>")    # Remove extra tags and added green colour to up arrow
    
    print(html_df)    #print the df
    

    在浏览器中输出文件:

    【讨论】:

    • 感谢@Chadila07 是否可以更改方向列的颜色,例如绿色表示向上,红色表示向下。
    • @aakashsingh 虽然您没有在问题中询问颜色,但是可以为箭头添加颜色。我已经编辑了我的答案,为箭头添加颜色也更新了输出。看看这个。
    • @aakashsingh 如果您认为它正确回答了您的问题,请接受答案。
    • @Chandila07:如果您仍然在 SO 上处于活动状态,我需要问您这不会产生如您的输出中所示的表格。相反,它向我展示了一个纯 html 标记代码。如何解决这个问题并查看您在此处显示的输出
    • @Django0602 在 cli 或控制台上,您只会将 html 视为文本,但如果想要 html 视图(渲染),则需要将 cli 输出重定向到扩展名为 .html 的某个文件并打开它在浏览器上。你可以看到我已经写了“浏览器中的输出文件”所以,这个输出你只会在浏览器中看到,因为它呈现了 html。我希望你明白我的意思...
    猜你喜欢
    • 2019-12-10
    • 2011-04-30
    • 2018-03-03
    • 1970-01-01
    • 2018-01-03
    • 2021-05-03
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多