栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

强制numpy创建对象数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

强制numpy创建对象数组

这是一个非常通用的方法:它适用于嵌套列表,数组列表列表-
不管这些数组的形状是不同还是相等。当数据聚集在一个单独的阵列中时,它也是有效的,这实际上是最棘手的情况。(到目前为止发布的其他方法在这种情况下不起作用。)

让我们从困难的情况开始,一个大数组:

# create example# pick outer shape and inner shape>>> osh, ish = (2, 3), (2, 5)# total shape>>> tsh = (*osh, *ish)# make data>>> data = np.arange(np.prod(tsh)).reshape(tsh)>>># recalculate inner shape to cater for different inner shapes# this will return the consensus bit of all inner shapes>>> ish = np.shape(data)[len(osh):]>>> # block them>>> data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh)>>> # admire>>> data_blockedarray([[array([[0, 1, 2, 3, 4],       [5, 6, 7, 8, 9]]),        array([[10, 11, 12, 13, 14],       [15, 16, 17, 18, 19]]),        array([[20, 21, 22, 23, 24],       [25, 26, 27, 28, 29]])],       [array([[30, 31, 32, 33, 34],       [35, 36, 37, 38, 39]]),        array([[40, 41, 42, 43, 44],       [45, 46, 47, 48, 49]]),        array([[50, 51, 52, 53, 54],       [55, 56, 57, 58, 59]])]], dtype=object)

使用OP的示例,它是数组列表的列表:

>>> x = np.array([[1, 2, 3], [4, 5, 6]])>>> y = np.array([[7, 8, 9], [0, 1, 2]])>>> u = np.array([[3, 4, 5], [6, 7, 8]])>>> v = np.array([[9, 0, 1], [2, 3, 4]])>>> data = [[x, y], [u, v]]>>> >>> osh = (2,2)>>> ish = np.shape(data)[len(osh):]>>> >>> data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh)>>> data_blockedarray([[array([[1, 2, 3],       [4, 5, 6]]),        array([[7, 8, 9],       [0, 1, 2]])],       [array([[3, 4, 5],       [6, 7, 8]]),        array([[9, 0, 1],       [2, 3, 4]])]], dtype=object)

还有一个具有不同形状子数组的示例(请注意

v.T
):

>>> data = [[x, y], [u, v.T]]>>> >>> osh = (2,2)>>> ish = np.shape(data)[len(osh):]>>> data_blocked = np.frompyfunc(np.reshape(data, (-1, *ish)).__getitem__, 1, 1)(range(np.prod(osh))).reshape(osh)>>> data_blockedarray([[array([[1, 2, 3],       [4, 5, 6]]),        array([[7, 8, 9],       [0, 1, 2]])],       [array([[3, 4, 5],       [6, 7, 8]]),        array([[9, 2],       [0, 3],       [1, 4]])]], dtype=object)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640961.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号