Python show HTML arrows to dataframe

跟風遠走 提交于 2020-02-25 05:09:27

问题


I created a datframe 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
. 
.
.

Now I am trying to replace the Direction value 0 by down arrow and 1 by up arrow. HTML code for down arrow is &#3219


回答1:


Try below code example:

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

Output file in browser:




回答2:


Use

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

Output

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


来源:https://stackoverflow.com/questions/52247052/python-show-html-arrows-to-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!