Python中如何以99999999为标记分割数组?迭代场景拆分需求
问题:按标记分割NumPy一维数组为子数组
我不清楚如何分割数组,分割标记为99999999。
我的代码
ssq=[] for i in range (12): for j in range (len(decision1[i])): w=uu[i][decision1[i][j]] ssq.append(w) j=j+1 ssq.append(99999999) i=i+1 ssq=np.array(ssq)
当前输出
array([ 0, 0, 1500, 1500, 1500, 1500, 1500, 1500, 0, 99999999, 0, 0, 0, 0, 0, 0, 0, 99999999, 0, 0, 0, 99999999, 500, 500, 500, 1000, 1000, 1000, 500, 2000, 99999999, 1000, 1000, 99999999,...])
目标输出
array([[0, 0, 1500, 1500, 1500, 1500, 1500, 1500, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0], [500, 500, 500, 1000, 1000, 1000, 500, 2000], [1000, 1000], ...])
我需要将当前的一维NumPy数组按99999999分割为多个子数组,对应每次迭代生成的元素集合。
解决方案
方案一:生成时直接构建子数组(更高效)
不需要先拼接成一维数组再分割,直接在循环中生成每个子数组,一步到位:
ssq = [] for i in range(12): sub_arr = [] for j in range(len(decision1[i])): w = uu[i][decision1[i][j]] sub_arr.append(w) ssq.append(sub_arr) # 因子数组长度不一致,用object类型存储 ssq = np.array(ssq, dtype=object)
方案二:对已有的一维数组进行分割
如果已经生成了带分割标记的一维数组,可以通过以下步骤拆分:
# 定位所有分割标记的索引 split_indices = np.where(ssq == 99999999)[0] # 切片分割数组 result = [] start_pos = 0 for idx in split_indices: result.append(ssq[start_pos:idx]) start_pos = idx + 1 # 转换为NumPy数组 result = np.array(result, dtype=object)
说明
np.where(ssq == 99999999)[0]会返回所有标记值的位置索引- 通过遍历索引,对原数组进行切片,得到每个子数组
- 由于子数组长度不同,需指定
dtype=object来存储
内容的提问来源于stack exchange,提问作者Agustin
相关产品推荐
相关产品推荐

