import numpy as np
import pandas as pd
# create an example array
a = np.arange(24).reshape([2,3,4])
# convert it to stacked format using Pandas
stacked = pd.Panel(a.swapaxes(1,2)).to_frame().stack().reset_index()
stacked.columns = ['x', 'y', 'z', 'value']
# save to disk
stacked.to_csv('stacked.csv', index=False)
np.ravel()
将其添加到您的数组中,然后使用此问题中的一种方法恢复索引。
def iter_3D(matrix):
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
for k in range(matrix.shape[2]):
yield i, j, k
l = []
for i, j, k in iter_3D(matrix):
l.append('%d %d %d %d' %(str(indices_x(i, j, k)), str(indices_y(i, j, k)), str(indices_z(i, j, k)), str(matrix[i, j, k]))
with open('file.csv', 'w') as f:
f.write("\n".join(l))