怎么解决 File "<__array_function__ internals>", line 200, in broadcast_arrays File "D:\Python-3.8\lib\site-packages\numpy\lib\stride_tricks.py", line 540, in broadcast_arrays shape = _broadcast_shape(*args) File "D:\Python-3.8\lib\site-packages\numpy\lib\stride_tricks.py", line 422, in _broadcast_shape b = np.broadcast(*args[:32]) ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (4,) and arg 1 with shape (3,).
时间: 2023-09-03 10:11:08 浏览: 1025
UNIX-Internals.rar_Internals_UNIX_Unix Internals 3rd_unix intern
你可以通过改变数组的形状来解决这个问题,使它们能够被广播到相同的形状。例如,你可以使用 `numpy.newaxis` 来为形状为 (4,) 的数组添加一个新的维度,使其变为形状为 (4, 1) 的二维数组,然后再进行广播操作。示例如下:
```python
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([1, 2, 3])
a = a[:, np.newaxis] # 将 a 转换为形状为 (4, 1) 的二维数组
c = a + b # 进行广播操作
print(c)
```
输出结果为:
```
array([[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7]])
```
这里将数组 a 转换为形状为 (4, 1) 的二维数组后,就可以和形状为 (3,) 的数组 b 进行广播操作了。
阅读全文