这是我的代码片段。它打印图像像素的平均值和标准偏差。
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} ")
输出是
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__
在这种情况下,如何定义数据的 f 字符串格式?
最佳答案
不幸的是,Python 的 f-string 不支持 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}"
sample 使用 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") )
输出 [[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
关于numpy - f numpy 数组的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60199696/