我使用下面的代码生成了一些测试数据:
import numpy as np
test_data = np.array(["[{:0.4f} {:0.4f} {:0.4f} {:0.4f} {:0.4f} {:0.4f}]".format(*np.random.uniform(low=-10, high=10, size=(6,))) for k in range(100)]).reshape(1,20,5)
这有望产生与您的阵列中的类似的东西。为了方便起见,我使用了 20,5 的尺寸 6000,200。
Numpy 在 char 模块中有一堆内置函数来帮助进行这种类型的处理,如 here 所示。
# Get rid of the (1,x,x) extra dimension
data_squeezed = np.squeeze(test_data)
data_squeezed.shape
# Returns (20, 5)
# data_squeezed[0,0] = '[-0.3523 -8.3259 -1.2245 -4.8143 8.1495 7.3349]'
# strip the leading and trailing brackets []
data_stripped = np.char.strip(data_squeezed, '[]')
# data_stripped[0,0] = '-0.3523 -8.3259 -1.2245 -4.8143 8.1495 7.3349'
# split the string into parts
data_split = np.char.split(data_stripped, ' ')
# data_split[0,0] = ['-0.3523', '-8.3259', '-1.2245', '-4.8143', '8.1495', '7.3349']
# convert the array of lists to an array
data_array_of_strings = np.array(data_split.tolist())
# data_array_of_strings[0,0] = array(['-0.3523', '-8.3259', '-1.2245', '-4.8143', '8.1495', '7.3349'], dtype='<U7')
# convert the string values to float values
data_array = data_array_of_strings.astype(float)
# data_array[0,0] = array([-0.3523, -8.3259, -1.2245, -4.8143, 8.1495, 7.3349])
# Or as a one liner
data_array = np.array(np.char.split(np.char.strip(np.squeeze(test_data), '[]'),' ').tolist()).astype(float)
# Check the shape
data_array.shape
# Returns (20,5,6) as required