用单引号将numpy数组中的数字分开,并用空格分隔

时间:2018-08-20 09:48:43

标签: python numpy

我试图用单引号将python中图像的像素值分隔为“对象”数据类型的numpy数组:

['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 .... 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] 

numpy数组的形状为1。

共有784个号码,但我无法单独访问它们。

我想要类似的东西

[238, 236, 237, ......, 70, 75, 90]为dtype int或float。

有1000个这样的numpy数组,如上面的数组。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用str.split

例如:

l = ['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] 
print( list(map(int, l[0].split())) )

输出:

[238, 236, 237, 238, 240, 240, 239, 241, 241, 243, 240, 239, 231, 212, 190, 173, 148, 122, 104, 92, 143, 136, 132, 127, 124, 119, 110, 104, 112, 119, 78, 20, 17, 19, 20, 23, 26, 31, 30, 30, 32, 33, 29, 30, 34, 39, 49, 62, 70, 75, 90]

答案 1 :(得分:0)

我相信使用np.ndarray.item()可以从numpy数组中检索单个项目。

import numpy as np
your_numpy_array = np.asarray(['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] )
values = your_numpy_array.item().split(' ')
new_numpy_array = np.asarray(values, dtype='int')

请注意,values是一个字符串列表。 np.asarray可以从字符串值列表中构造一个整数数组,我们只需要指定dtype(由hpaulj建议)