如何从嵌套数组中移除不必要的层级?
我有一个高度嵌套的NumPy数组,如下所示:
array = [
[
[
[ "data . . . "],
]
],
[
[
["more data . . ."],
]
]
]
并且想去掉几层,将其变成:
array = [
[ "data . . . "],
["more data . . ."]
]
如何高效地使用NumPy来实现这一点?
如果我使用列表推导式,我会直接这么写:
a_flat = [ row[0][0] for row in array ]
解决方案
你展示的是一个普通的列表并请求 numpy,但为确保:
每个列表必须具有相同的维度。
它不能是,例如 ["data . . . "](只有一个项)
而是 ["more data . . . ", "A", "B", "C"](4项)
numpy 有 array.flatten(),但这会产生
['data . . . ', 'more data . . .']
但是使用 array.reshape(),你可以转换为期望的大小。
array.reshape(-1, 1) 会给我
[['data . . . '], ['more data . . .']]
但如果数据更多,你需要先知道第一维和/或最后一维
last = arr.shape[-1]
arr.reshape(-1, last)
first = arr.shape[0]
arr.reshape(first, -1)
但这一切都需要将嵌套列表转换为 np.array(),然后再用 .tolist() 转换回去
带有更多数据的最小可运行代码
import numpy as np
array = [
[
[
["data . . . ", "B"],
]
],
[
[
["more data . . .", "B"],
]
],
[
[
["more data . . .", "B"],
]
],
[
[
["more data . . .", "B"],
]
],
]
arr = np.array(array)
print("flatten:", arr.flatten().tolist())
print("shape:", arr.shape)
#print("reshape:", arr.reshape(-1, 1).tolist())
last = arr.shape[-1]
print("reshape:", arr.reshape(-1, last).tolist())
first = arr.shape[0]
print("reshape:", arr.reshape(first, -1).tolist())
flatten: ['data . . . ', 'B', 'more data . . .', 'B', 'more data . . .', 'B', 'more data . . .', 'B']
shape: (4, 1, 1, 2)
reshape: [['data . . . ', 'B'], ['more data . . .', 'B'], ['more data . . .', 'B'], ['more data . . .', 'B']]
reshape: [['data . . . ', 'B'], ['more data . . .', 'B'], ['more data . . .', 'B'], ['more data . . .', 'B']]
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。