如何在Python中转置不规则(锯齿状)二维数组?
转置不规则(锯齿状)NumPy数组的可行方案
你的需求完全可行,由于NumPy的transpose函数仅适用于规则形状的数组,而原生zip会以最短子数组长度截断,所以需要结合Python原生工具处理:
方法一:手动按列收集元素
先将NumPy对象数组转为Python列表,再遍历每一列索引收集有效元素:
import numpy as np seats = np.array([ [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2, 3, 4], [1, 2], [1, 2] ], dtype = object) # 转换为Python列表便于处理 seats_list = seats.tolist() # 获取最长子数组的长度,确定转置后的列数 max_col = max(len(row) for row in seats_list) transposed_list = [] for col_idx in range(max_col): # 收集所有行中存在该列索引的元素 current_col = [row[col_idx] for row in seats_list if col_idx < len(row)] transposed_list.append(current_col) # 转换回NumPy对象数组 transposed_seats = np.array(transposed_list, dtype=object)
方法二:利用itertools.zip_longest简化代码
借助zip_longest对齐所有子数组,再过滤填充的空值:
import numpy as np from itertools import zip_longest seats = np.array([ [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2, 3, 4], [1, 2], [1, 2] ], dtype = object) seats_list = seats.tolist() # 用zip_longest对齐所有行,填充None transposed_list = [] for group in zip_longest(*seats_list, fillvalue=None): # 过滤掉填充的None,保留有效元素 current_col = [val for val in group if val is not None] transposed_list.append(current_col) transposed_seats = np.array(transposed_list, dtype=object)
两种方法最终生成的transposed_seats都完全符合你期望的格式:
array([[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4], [5]], dtype=object)
内容的提问来源于stack exchange,提问作者Wunderkind
相关产品推荐
相关产品推荐

