[英]styling a pandas dataframe in python makes the float values have more zeros after the decimal point
這是我的樣式代碼,使正數顯示為綠色,負數顯示為紅色,如果我只是打印出 df 它會顯示如下數字:
25.72,36.28,0.17
使用樣式,但是它們顯示如下:25.7200000, 36.2800000, 0.1700000
我怎樣才能讓它們看起來像以前一樣,但有五顏六色的風格? 謝謝你的幫助,我對 python 真的很陌生
def color_negative_red(value):
if isinstance(value, str):
color = 'black'
return 'color: %s' % color
if isinstance(value, float):
if value > 0:
color = "green"
return 'color: %s' % color
if value < 0:
color = "red"
return 'color: %s' % color
df.style.applymap(color_negative_red)
您可以通過Styler.format
中的字典指定浮點列的格式:
df = pd.DataFrame({'a': [25.72,36.28,0.17], 'b': [9.7,-9, 9.8], 'c':list('abc')})
def color_negative_red(value):
if isinstance(value, str):
color = 'black'
return 'color: %s' % color
if isinstance(value, float):
if value > 0:
color = "green"
return 'color: %s' % color
if value < 0:
color = "red"
return 'color: %s' % color
d = dict.fromkeys(df.select_dtypes('float').columns, "{:.2%}")
df.style.applymap(color_negative_red).format(d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.