在 python 中设置 pandas 数据帧的样式使得浮点值在小数点后有更多的零
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)
您可以指定format for floats columns by dictionary in 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)
这是我的样式代码,让正数显示为绿色,负数显示为红色 如果我只是打印出 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)
您可以指定format for floats columns by dictionary in 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)