将3D numpy数组写入包括其索引的文件

时间:2014-12-16 13:05:35

标签: python arrays numpy

我对此很新,所以道歉但希望我的语法合适,所以你理解我的问题! 我有一个形状为(2,2,2)的numpy数组

array([[[ 1, 1],
        [ 2, 2]],

       [[ 3, 3],
        [ 4, 4]]])

如何将其写入文件,以便列出索引和数组值 即

0 0 0 1
1 0 0 3
0 1 0 2
1 1 0 4
0 0 1 1
1 0 1 3
0 1 1 2
1 1 1 4

感谢, 英格丽。

2 个答案:

答案 0 :(得分:1)

您可以使用numpy.ndenumerate

a = np.array([[[1, 1],
               [2, 2]],

              [[3, 3],
               [4, 4]]])

for items in np.ndenumerate(a):
    print(items)

输出

((0, 0, 0), 1)
((0, 0, 1), 1)
((0, 1, 0), 2)
((0, 1, 1), 2)
((1, 0, 0), 3)
((1, 0, 1), 3)
((1, 1, 0), 4)
((1, 1, 1), 4)

要删除括号,您可以解压缩所有内容

for indexes, value in np.ndenumerate(a):
    x,y,z = indexes
    print(x,y,z,value)

输出

0 0 0 1
0 0 1 1
0 1 0 2
0 1 1 2
1 0 0 3
1 0 1 3
1 1 0 4
1 1 1 4

处理文件写作

with open('file.txt', 'w') as f:
    for indexes, value in np.ndenumerate(a):
        x,y,z = indexes
        f.write('{} {} {} {}\n'.format(x,y,z,value))

答案 1 :(得分:0)

不确定这是否是在NumPy中执行此操作的最佳方式,但您可以使用numpy.unravel_indexnumpy.dstacknumpy.savetxt的组合执行此操作:

>>> arr = np.array([[[ 1, 1],
        [ 2, 2]],

       [[ 3, 3],
        [ 4, 4]]])
>>> a = np.dstack(np.unravel_index(np.arange(arr.size),
                                                   arr.shape) + (arr.ravel(),))
>>> np.savetxt('foo.txt', a[0,...], fmt='%d')
>>> !cat foo.txt
0 0 0 1
0 0 1 1
0 1 0 2
0 1 1 2
1 0 0 3
1 0 1 3
1 1 0 4
1 1 1 4