python - numpy 将数组与索引排序结合起来
问题描述
我想按索引的顺序组合多个 numpy 数组。这就是我的意思:假设我有两个像
>>> a = [0, 1, 2, 3]
>>> b = [-5, -6, -7, -8]
如何组合这些数组以使输出为
c = np.combination_function((a,b))
>>> c = [0 -5, 1, -6, 2, -7, 3, -8]
concatenate
并将彼此append
放置a
和b
“相邻”,这不是我想要的。
Numpyrepeat
和tile
函数在此用作类比。例如
np.repeat([3, 4, 2], 2)
>>> [3, 3, 4, 4, 2, 2] # two 3's, then two 4's, then two 2's. This is what I want
np.tile([3, 4, 2], 2)
>>> [3, 4, 2, 3, 4, 2] # [3,4,2] twice. This is not what I want
tile
照concatenate
原样repeat
_???
一个办法:
我已经能够做到这一点
c = np.stack((a,b)).flatten('F')
有一个更好的方法吗?
解决方案
你的解决方案非常好。您可以通过按 FORTRAN 顺序进行堆叠来加快速度:
timeit(lambda:np.stack([a,b]).flatten("F"))
# 11.13118030806072
timeit(lambda:np.array([a,b],order="F").ravel(order="K"))
# 3.0580440941266716
推荐阅读
- elasticsearch - 是否可能仅在弹性搜索中的某些字段上具有模糊性?
- sql-server - 问号在 SQL 查询中的作用是什么?
- node.js - 使用从 req.params 中获取的集合 - node.js
- azure-devops - 如何在不覆盖现有标签的情况下向 Azure Devops 中的工作项添加标签?
- amazon-web-services - S3 和云端的重定向规则
- ag-grid-angular - ag-grid getFilterModel 总是按名称返回顺序
- php - 产品过滤器和所有产品都没有显示在页面上,即使它是通过管理面板放置的
- mysql - 带有存储功能的 SQL 嵌套查询
- python - 触发和运行 python 脚本的服务?
- math - 是否有一个身份可以找到 (x mod a) + (x mod b) + (x mod c) ...?