简体   繁体   中英

Separate the numbers in a numpy array which are in single quote separated by spaces

I am trying to separate the pixel values of an image in python which are in a numpy array of 'object' data-type in a single quote like this:

['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'] 

The shape of the numpy array is coming as 1.

There are a total of 784 numbers but I cannot access them individually.

I wanted something like:

[238, 236, 237, ......, 70, 75, 90] of dtype int or float.

There are 1000 such numpy arrays like the one above.

Thanks in advance.

You can use str.split

Ex:

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())) )

Output:

[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]

I believe using np.ndarray.item() is idiomatic to retrieve a single item from a numpy array.

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')

Note that values here is a list of strings. np.asarray can construct an array of integers from list of string values, we just need to specify the dtype (as suggested by hpaulj )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM