python - 如何在没有换行符的情况下打印numpy对象

标签 python logging numpy

我正在使用函数记录输入参数

logging.debug('Input to this function = %s',
              inspect.getargvalues(inspect.currentframe())[3])

但我不想在 numpy 对象中插入换行符。 numpy.set_printoptions(linewidth=np.nan) 去掉了一些,但是在二维对象中还是会插入换行符比如

array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ],
       [ 0.68041249,  0.20310698,  0.89486761,  0.97799646],
       [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

我希望它是这样的:

array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ], [ 0.68041249,  0.20310698,  0.89486761,  0.97799646], [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

我该怎么做?谢谢。

最佳答案

给定一个数组x,你可以不换行打印它,

import numpy as np
x_str = np.array_repr(x).replace('\n', '')
print(x_str)

或者使用函数 np.array2string 而不是 np.array_repr

我不确定是否有一种简单的方法可以从字符串表示或 numpy 数组中删除换行符。但是,始终可以在转换发生后删除它们,

input_args = inspect.getargvalues(inspect.currentframe())[3]
logging.debug('Input to this function = %s', repr(input_args).replace('\n', ''))

关于python - 如何在没有换行符的情况下打印numpy对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29102955/

相关文章:

Python: "ModuleNotFoundError",但是安装了模块?

python - 过滤掉包含特定字符串的数据帧的行

c# - 我应该将 ILogger、ILogger<T>、ILoggerFactory 还是 ILoggerProvider 作为库使用?

linux - 是否有等同于 Windows >log.txt 的 Linux 用于将命令输出记录到文件?

python - 为什么 x <= x 为假?

python - 从过程中排除某些尺寸的图像(OpenCV、Python)

macos - AppleScript 编辑器,将消息写入 "Result"窗口

python - 对 scipy.sparse.csr_matrix 中的行求和

python - 任何加速从磁盘读取数据并将其转换为 numpy 数组以供进一步处理的解决方案?

python - 创建一个公开Python代码的DLL