【问题标题】:Can I print a numpy array's values in green if positive and red if negative?如果为正,我可以用绿色打印一个 numpy 数组的值,如果为负,我可以打印红色吗?
【发布时间】:2026-01-08 03:40:01
【问题描述】:

在将一个 numpy 浮点数组打印到控制台时,我想要一个快速的视觉提示。如何使用颜色来表示积极/消极?

我发现了这种更改控制台颜色的 hacky 方法,但我不确定它对我的情况是否有用:

>>>YELLOW = '\033[93m'
>>>ENDCOLOR = '\033[0m'
>>>print(YELLOW+'hello'+ENDCOLOR)
hello # <-- this is yellow
>>>this is in your regular console color

但是如果你省略了最后一个字符串:

>>>YELLOW = '\033[93m'
>>>ENDCOLOR = '\033[0m'
>>>print(YELLOW+'hello')
hello #<-- it's yellow
>>>this is yellow as well, until you print ENDCOLOR

【问题讨论】:

  • 我认为您需要编写一个自定义函数来打印数组元素以及所需的 ANSI 代码。

标签: python numpy colors


【解决方案1】:

按照 Vikas Damodar 的建议,最干净的方法是使用 np.set_printoptions 和 colorama 中的格式化程序 kwarg:

import colorama
import numpy as np

def color_sign(x):
    c = colorama.Fore.GREEN if x > 0 else colorama.Fore.RED
    return f'{c}{x}'

np.set_printoptions(formatter={'float': color_sign})

请注意,这是一个全局配置,将使用此约定打印所有数组。

【讨论】:

  • 有效!而我只是在程序末尾添加print('\033[0m') 来恢复默认的控制台颜色。
  • 您可以简单地使用colorama.Fore.RESET,它也可以在其他平台上使用。
  • 是的,看起来更好
【解决方案2】:

我认为colorama 是一个很好的方法:

from colorama import fore

print(f'{fore.Green}green color')

【讨论】:

    最近更新 更多