[英]Python: How to convert Numpy array item value type to array with this value?
What is the best way to convert such ndarray: 转换此类ndarray的最佳方法是什么:
[[1,2,3], [4,5,6]]
to the: 到:
[[[1],[2],[3]], [[4],[5],[6]]]
just wrap each value to array 只需将每个值包装到数组
You can introduce a new axis with np.newaxis/None
at the end, like so - 您可以在末尾添加np.newaxis/None
来引入新轴,如下所示-
arr[...,None]
Sample run - 样品运行-
In [6]: arr = np.array([[1,2,3], [4,5,6]])
In [7]: arr[...,None]
Out[7]:
array([[[1],
[2],
[3]],
[[4],
[5],
[6]]])
In [8]: arr[...,None].tolist() # To show it as a list for expected o/p format
Out[8]: [[[1], [2], [3]], [[4], [5], [6]]]
You can do it by recursively exploring the list of lists: 您可以通过递归浏览列表列表来做到这一点:
def wrap_values(list_of_lists):
if isinstance(list_of_lists, list):
return [wrap_values(el) for _,el in enumerate(list_of_lists)]
else:
return [list_of_lists]
xx = [[1,2,3], [4,5,6]]
yy = wrap_values(xx) # [[[1], [2], [3]], [[4], [5], [6]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.