python - numpy 整数数组转换为 numpy 数组数组
问题描述
我想将 numpy 数组转换为 numpy 数组数组。
我有一个数组:a = [[0,0,0],[0,255,0],[0,255,255],[255,255,255]]
我想拥有:b = [[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[255,255,255],[0,0,0]],[[0,0,0],[255,255,255],[255,255,255]],[[255,255,255],[255,255,255],[255,255,255]]]
有什么简单的方法吗?
我已经尝试过,np.where(a == 0, [0,0,0],[255,255,255])
但出现以下错误:
ValueError: operands could not be broadcast together with shapes
解决方案
您可以broadcast_to
用作
b = np.broadcast_to(a, (3,4,3))
a
形状在哪里(3,4)
。然后你需要交换轴
import numpy as np
a = np.array([[0,0,0],[0,255,0],[0,255,255],[255,255,255]])
b = np.broadcast_to(a, (3,4,3))
c = np.moveaxis(b, [0,1,2], [2,0,1])
c
给予
array([[[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]],
[[ 0, 0, 0],
[255, 255, 255],
[ 0, 0, 0]],
[[ 0, 0, 0],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]])
@Divakar 建议的更直接的方法广播方法是
b = np.broadcast(a[:,:,None], (4,3,3))
它在没有轴交换的情况下产生相同的输出。
推荐阅读
- laravel - Laravel Guest-checkout is not working in paypal using "paypal/rest-api-sdk-php": "*" this package also success response is not getting on it
- ios - SINCH SDK 带宽
- postgresql - 是否可以在 Postgresql 中更改另一个会话的设置?
- linux - 使用 perl 脚本在目录中查找文件
- java - 如何使用 Lambda 将列表列表转换为 Java 中的 Hashset
- excel - 如何根据匹配值对所有值求和?
- ios - SwiftUI - 什么是 ZStack,它与 VStack 有什么区别?
- javascript - 从 Flask 后端选择选项值到 React 前端
- jquery - 如果第一次调用的条件为假,则在另一个 ajax 调用中进行 ajax 调用
- laravel - 未找到 Laravel 包类