arrays - 在 Python 中从 2 个单维数组创建 2d 数组
问题描述
我有 2 个一维 NumPy 数组
a = np.array([0, 4])
b = np.array([3, 2])
我想创建一个二维数字数组
c = np.array([[0,1,2], [4,5]])
我也可以使用 for 循环创建它
编辑:根据@jtwalters评论更新循环
c = np.zeros(b.shape[0], dtype=object)
for i in range(b.shape[0]):
c[i] = np.arange(a[i], a[i]+b[i])
如何通过矢量化/广播实现这一目标?
解决方案
要从参差不齐的嵌套序列创建 ndarray,您必须将dtype=object
.
例如:
c = np.empty(b.shape[0], dtype=object)
for i in range(b.shape[0]):
c[i] = np.arange(a[i], a[i]+b[i])
或使用数组:
np.array([np.arange(a[i], a[i]+b[i]) for i in range(b.shape[0])], dtype=object)
矢量化:
def func(a, b):
return np.arange(a, a + b)
vfunc = np.vectorize(func, otypes=["object"])
vfunc([0, 4], [3, 2])
推荐阅读
- c++ - 为什么我得到“候选构造函数不可行”?
- html - 在移动视图中引导 4 张单独的卡片?
- java - JADE IPMS:代理迁移失败
- swift - 无法以编程方式将情节提要中的颜色集更改为 xcassets 目录中的颜色
- python - 使用 f String 插入字符或符号@
- c++ - 如何在 C++ arduino 中从字符串中拆分特定部分
- opendaylight - 铍发布无法在 Web 界面上登录 (http://10.10.10.2:8181/index.html)
- angular - Angular 7 - 未捕获(承诺):错误:StaticInjectorError(AppModule)[BASE_URL]
- javascript - 为什么我的 Jest 测试通过然后在创建 TypeError 之后调用该函数
- python - Python - Croniter - 必须为迭代器表达式指定正好 5 或 6 列