Trying to convert a list to 1D array and that list contain arrays like this
from
[array([1145, 330, 1205, 364], dtype=int64),
array([1213, 330, 1247, 364], dtype=int64),
array([ 883, 377, 1025, 412], dtype=int64),
array([1038, 377, 1071, 404], dtype=int64),
array([1085, 377, 1195, 405], dtype=int64),
array([1210, 377, 1234, 405], dtype=int64)]
Required
array([array([1145, 330, 1205, 364], dtype=int64),
array([[1213, 330, 1247, 364], dtype=int64),
array([883, 377, 1025, 412], dtype=int64),
array([1038, 377, 1071, 404], dtype=int64),
array([1085, 377, 1195, 405], dtype=int64),
array([1085, 377, 1195, 405], dtype=int64), dtype=object))
tried this code but getting 2D array but need 1D array like above
art = []
for i in boxs:
art.append(np.array(i, dtype=np.int64))
new_ary = np.array(art)
new_ary
CodePudding user response:
Your question is little ambiguous. Your input is already a 2D and in
for i in boxs:
art.append(np.array(i, dtype=np.int64))
i
represents a list in each iteration. So, You are appending a list each time in art
.
You can try new_ary = new_ary.flatten()
. It will give you
[1145 330 1205 364 1213 330 1247 364 883 377 1025 412 1038 377 1071 404 1085 377 1195 405 1210 377 1234 405]
Otherwise, provide an output to clarify your question.
CodePudding user response:
While you are changing the list of arrays to an array of arrays with dtype=object
, the value in the array is still int.
np.array(a, dtype=object)
array([[1145, 330, 1205, 364],
[1213, 330, 1247, 364],
[883, 377, 1025, 412],
[1038, 377, 1071, 404],
[1085, 377, 1195, 405],
[1210, 377, 1234, 405]], dtype=object)
type(np.array(a, dtype=object)[0][0])
Out[151]: int
Update
If you want to flatten the 2D array to a 1D array, you can use np.ravel
np.ravel(a)
array([1145, 330, 1205, 364, 1213, 330, 1247, 364, 883, 377, 1025,
412, 1038, 377, 1071, 404, 1085, 377, 1195, 405, 1210, 377,
1234, 405], dtype=int64)
Or let's say you want a 1D list, you can first do map
to convert the array to list and then do reduce
from functools import reduce
mylist = list(map(list, a))
print(reduce((lambda x, y: x y) , mylist))
[1145, 330, 1205, 364, 1213, 330, 1247, 364, 883, 377, 1025, 412, 1038, 377, 1071, 404, 1085, 377, 1195, 405, 1210, 377, 1234, 405]