按列将二维 numpy 浮点数组转换为字符串数组
Convert 2-d numpy array of floats to array of strings by column
我有一个 NumPy 数组,它是 TensorFlow 预测的输出。输出看起来像这样:
array([[0, 1, 1, ..., 1, 1, 1],
[0, 1, 1, ..., 1, 1, 1],
[0, 1, 1, ..., 1, 1, 1],
...,
[1, 1, 1, ..., 1, 1, 1],
[1, 1, 1, ..., 1, 1, 1],
[1, 1, 1, ..., 1, 1, 1]])
为了进一步处理,应将二维 NumPy 数组转换为一维字符串数组(或 python 列表)。输出应如下所示:
array(['01111111', '01111111', '01111111', ..., '11111111', '11111111',
'11111111'], dtype='<U8')
实现此目标的简单方法或 NumPy 最佳实践方法是什么?
试试这个:
import numpy as np
arr = np.array([[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]])
output = np.array([''.join(map(str, el)) for el in arr], dtype='U8')
print(output)
输出:
['011111' '011111' '011111' '111111' '111111' '111111']
您可以像下面这样使用 apply_along_axis
:
短版:
a = np.array([[0, 1, 1, 0, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1]])
np.apply_along_axis(''.join, 1, a.astype(str))
解释版:
def join_num(r):
return ''.join(map(str,r))
# or with lamda
# join_num = lambda x: ''.join(map(str,x))
np.apply_along_axis(join_num, 1, a)
输出:
array(['0110111', '0111111', '0110111', '1111111', '1110111', '1111111'],
dtype='<U7')
假设数组名为 array
并且 numpy 被导入为 np
,以下行:
np.apply_along_axis(''.join, 1, array.astype(str))
就够了
我有一个 NumPy 数组,它是 TensorFlow 预测的输出。输出看起来像这样:
array([[0, 1, 1, ..., 1, 1, 1],
[0, 1, 1, ..., 1, 1, 1],
[0, 1, 1, ..., 1, 1, 1],
...,
[1, 1, 1, ..., 1, 1, 1],
[1, 1, 1, ..., 1, 1, 1],
[1, 1, 1, ..., 1, 1, 1]])
为了进一步处理,应将二维 NumPy 数组转换为一维字符串数组(或 python 列表)。输出应如下所示:
array(['01111111', '01111111', '01111111', ..., '11111111', '11111111',
'11111111'], dtype='<U8')
实现此目标的简单方法或 NumPy 最佳实践方法是什么?
试试这个:
import numpy as np
arr = np.array([[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]])
output = np.array([''.join(map(str, el)) for el in arr], dtype='U8')
print(output)
输出:
['011111' '011111' '011111' '111111' '111111' '111111']
您可以像下面这样使用 apply_along_axis
:
短版:
a = np.array([[0, 1, 1, 0, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1]])
np.apply_along_axis(''.join, 1, a.astype(str))
解释版:
def join_num(r):
return ''.join(map(str,r))
# or with lamda
# join_num = lambda x: ''.join(map(str,x))
np.apply_along_axis(join_num, 1, a)
输出:
array(['0110111', '0111111', '0110111', '1111111', '1110111', '1111111'],
dtype='<U7')
假设数组名为 array
并且 numpy 被导入为 np
,以下行:
np.apply_along_axis(''.join, 1, array.astype(str))
就够了