将ndarray转换为字符串并逐行打印

时间:2017-01-24 16:34:08

标签: python arrays python-2.7 multidimensional-array

我正在尝试使用ndarray类型打印变量cp。

type(cp) 
print cp

    Output:
    <type 'numpy.ndarray'>
    [ 2500.          2498.9888893   2497.86349278  2496.614551    2495.23344426
      2493.71218042  2492.04338019  2490.22025987  2488.23661229  2486.08678611
      2483.76566391  2481.26863949  2478.59159445  2475.73087472  2472.68326689
      2469.44597486  2466.01659689  2462.39310325  2458.57381455  2454.55738096
      2450.34276235  2445.92920938]

我想将输出打印为:

    2500
    2498.98
    2497.86
    ....
    ...

如何将ndarray转换为str并按照所示进行打印?

1 个答案:

答案 0 :(得分:1)

你可以迭代一个numpy数组。

循环播放:

for n in a:
    print("  %.2f" % n)

作为一个单行:

print("\n".join("  %.2f" % n for n in a))

示例数据:

a = np.array([
    2500., 2498.9888893, 2497.86349278, 2496.614551, 2495.23344426,
    2493.71218042, 2492.04338019, 2490.22025987, 2488.2366123, 2486.0867861,
    2483.76566391, 2481.26863949, 2478.59159445, 2475.7308747, 2472.6832669,
    2469.44597486, 2466.01659689, 2462.39310325, 2458.5738145, 2454.557380,
    2450.34276235, 2445.92920938
])