Numpy 1.24中np.stack处理Astropy量失效问题咨询
问题:NumPy 1.24.3中结合Astropy Units使用np.stack报错的原因
复现代码
以下代码在NumPy 1.23.5中可正常运行,但在NumPy 1.24.3中报错:
from astropy import units as u import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 6], [7, 8]]) np.stack([a,b]*u.m)
错误栈信息
在NumPy 1.24.3中触发的错误:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<__array_function__ internals>", line 200, in stack File "~/opt/anaconda3/lib/python3.9/site-packages/astropy/units/quantity.py", line 1683, in __array_function__ return super().__array_function__(function, types, args, kwargs) File "~/opt/anaconda3/lib/python3.9/site-packages/numpy/core/shape_base.py", line 471, in stack return _nx.concatenate(expanded_arrays, axis=axis, out=out, File "<__array_function__ internals>", line 200, in concatenate File "~/opt/anaconda3/lib/python3.9/site-packages/astropy/units/quantity.py", line 1688, in __array_function__ args, kwargs, unit, out = function_helper(*args, **kwargs) TypeError: concatenate() got an unexpected keyword argument 'dtype'
预期正常结果
在NumPy 1.23.5中运行的正确输出:
<Quantity [[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]] m>
原因分析及解决办法
这既不是操作错误,也不是NumPy 1.24的bug,而是Astropy Units模块需要适配NumPy 1.24的API变更:
- NumPy 1.24对
concatenate函数新增了dtype关键字参数,旧版本Astropy的Quantity类在处理__array_function__时,其function_helper方法未兼容该新增参数,导致抛出参数不匹配的错误。
解决方式:
- 升级Astropy版本:将Astropy升级到5.2及以上版本,这些版本已修复与NumPy 1.24的兼容性问题。
- 临时替代方案:先将单个数组转换为Quantity对象,再执行堆叠操作,修改后的代码如下:
np.stack([a*u.m, b*u.m])
内容的提问来源于stack exchange,提问作者Dunbur
相关产品推荐
相关产品推荐

