You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Numpy将0维(标量)、1维、2维数组写入CSV的解决方案求助

问题原因

np.savetxt 原生要求输入数组至少为1维,直接传入0维numpy标量时会触发维度校验错误。

解决方案

写入前对数组做维度兼容处理,使用np.atleast_2d()方法可将任意维度的numpy数组统一转为2维格式,不会改变原有数据的排布逻辑,同时兼容0维、1维、2维输入。

修改后的代码如下:

for key in testfiles:
    tname = key + ".csv"
    # 统一兼容多维度输入
    compatible_arr = np.atleast_2d(testfiles[key])
    np.savetxt(tname, compatible_arr, delimiter=",", newline=';', fmt='%0.15f')

可选调整

如果你希望1维数组在CSV中按单列存储而非单行存储,可以额外增加维度转置判断:

for key in testfiles:
    tname = key + ".csv"
    raw_arr = testfiles[key]
    if raw_arr.ndim == 1:
        compatible_arr = raw_arr.reshape(-1, 1)
    else:
        compatible_arr = np.atleast_2d(raw_arr)
    np.savetxt(tname, compatible_arr, delimiter=",", newline=';', fmt='%0.15f')

内容的提问来源于stack exchange,提问作者Mykenk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:15:04