f numpy 数组的字符串格式

pas*_*ion 6 formatting numpy pixel

这是我的代码片段。它打印图像像素的平均值和标准偏差。

from numpy import asarray
from PIL import Image
import os

os.chdir("../images") 
image = Image.open("dubai_2020.jpg")
pixels = asarray(image) 
pixels = pixels.astype("float32")
means, stds = pixels.mean(axis=(0, 1), dtype="float64"), pixels.std(
    axis=(0, 1), dtype="float64")
print(f"Means: {means:%.2f}, Stds: {stds:%.2f} ")
Run Code Online (Sandbox Code Playgroud)

输出是

 File "pil_local_standard5.py", line 15, in <module>
    print(f"Means: {means:%.2f, %.2f, %.2f}, Stds: {stds:%.2f, %.2f, %.2f} ")

TypeError: unsupported format string passed to numpy.ndarray.__format__
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如何定义数据的 f 字符串格式?

AGN*_*zer 8

我认为完成与您想要的类似的事情的最简单方法目前需要使用numpy.array2string.

例如,假设means = np.random.random((5, 3)). 然后你可以这样做:

import numpy as np
means = np.random.random((5, 3)).astype(np.float32)  # simulate some array
print(f"{np.array2string(means, precision=2, floatmode='fixed')}")
Run Code Online (Sandbox Code Playgroud)

这将打印:

[[0.41 0.12 0.84]
 [0.28 0.43 0.29]
 [0.68 0.41 0.14]
 [0.75 1.00 0.16]
 [0.30 0.49 0.37]]
Run Code Online (Sandbox Code Playgroud)

可以通过以下方式实现同​​样的效果:

print(f"{np.array2string(means, formatter={'float': lambda x: f'{x:.2f}'})}")
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您还可以添加分隔符:

print(f"{np.array2string(means, formatter={'float': lambda x: f'{x:.2f}'}, separator=', ')}")
Run Code Online (Sandbox Code Playgroud)

这将打印:

[[0.41, 0.12, 0.84],
 [0.28, 0.43, 0.29],
 [0.68, 0.41, 0.14],
 [0.75, 1.00, 0.16],
 [0.30, 0.49, 0.37]]
Run Code Online (Sandbox Code Playgroud)


Seb*_*sen 1

不幸的是,Python 的 f 字符串不支持 numpy 数组的格式化。


我想出的一个解决方法:

def prettifyStr(numpyArray, fstringText):
  num_rows = numpyArray.ndim
  l = len(str(numpyArray))
  t = (l // num_rows)
  diff_to_center_align = 50 - t
  return f"{str(numpyArray)}{' ': <{diff_to_center_align}}{fstringText}"
Run Code Online (Sandbox Code Playgroud)

样品使用

    print( prettifyStr(a2, "this is some text") )
    print( prettifyStr(a3, "this is some text") )
    print( prettifyStr(a1, "this is some text") )
    print( prettifyStr(a4, "this is some text") )
Run Code Online (Sandbox Code Playgroud)

输出

[[0.  3.  4. ]
 [0.  5.  5.1]]                                   this is some text 

[[0.   3.   4.   4.35]
 [0.   5.   5.1  3.6 ]]                           this is some text 

[[0 3]
 [0 5]]                                           this is some text 

[[0.   3.   4.   4.35 4.25]
 [0.   5.   5.1  3.6  3.1 ]]                      this is some text
Run Code Online (Sandbox Code Playgroud)