Python 从三维阵列写入多个文件

Python 从三维阵列写入多个文件,python,arrays,file,numpy,numpy-ndarray,Python,Arrays,File,Numpy,Numpy Ndarray,我有一个形状为:(766L,256L,256L)的3D数组,我需要为数组中的766个切片中的每一个创建一个文件,以下是我的代码: import numpy as np import pyfits as fit data = fit.open('lsb_0299170159_0x53c_sci.fit') scidata=data[0].data #Here is the data print scidata #This is a part of the data to show the

我有一个形状为:(766L,256L,256L)的3D数组,我需要为数组中的766个切片中的每一个创建一个文件,以下是我的代码:

import numpy as np
import pyfits as fit

data = fit.open('lsb_0299170159_0x53c_sci.fit')
scidata=data[0].data     #Here is the data
print scidata #This is a part of the data to show the structure

>>>[[[  1.93521921e-02   5.53070288e-03   5.54129062e-03 ...,   7.59920711e-
03
 7.43154995e-03   9.53296479e-03]
[  5.75147476e-03   6.56543719e-03   6.83003664e-03 ...,   4.90503712e-03
   5.36678405e-03   3.56429932e-03]
[  4.48714197e-03   6.52663829e-03   6.36298675e-03 ...,   5.20661334e-03
   4.07732278e-03   8.60160124e-03]
..., 
[  3.72386798e-02   3.89487632e-02   3.83604541e-02 ...,   6.86576292e-02
   7.70815611e-02   8.00874010e-02]
[  3.48356217e-02   3.67552601e-02   3.45812403e-02 ...,   7.06715509e-02
   6.99861422e-02   7.58737400e-02]
[  3.13520059e-02   3.35403681e-02   3.80725004e-02 ...,              nan
              nan              nan]]

[[  1.93521921e-02   1.42930017e-03   1.38372893e-03 ...,   1.31980027e-03
    1.37834414e-03   1.39542914e-03]
 [  1.73271971e-03   1.41039363e-03   1.52022589e-03 ...,   1.29821908e-03
    1.20712281e-03   1.24027242e-03]
 [  1.73819589e-03   1.48109102e-03   1.49079110e-03 ...,   1.19586918e-03
    1.21934328e-03   1.35999266e-03]
 ..., 
 [  3.46756959e-03   3.67738772e-03   3.22443643e-03 ...,   4.02061298e-04
    6.46648754e-04   7.07142055e-04]
 [  3.69005208e-03   3.11211054e-03   3.23838764e-03 ...,   5.41916583e-04
    4.33047127e-04   5.89787844e-04]
 [  3.40519636e-03   3.49198561e-03   3.19557916e-03 ...,              nan
               nan              nan]]

for i in range(scidata.shape[0]):

    with open('leisa1{}.csv'.format(i), "wb") as outfile:

       np.savetxt(outfile,i,fmt='%.5f',delimiter=' ',footer='====')
但是在运行之后,我得到了下一个错误,(我编辑了下面的内容,第一个错误消失了,但现在它显示了):

问题在于:

for i in scidata:
上面的循环每次将为您提供766个切片中的一个,而不是创建
.csv
文件时使用的索引

因此,将该行更改为

for i in range(scidata.shape[0]):
    # code follows
或如评论中所述,使用:

for idx, slice in enumerate(scidata):
    # code follows

#1.修复缩进#2你认为这个错误是什么意思?这很奇怪,你确定你没有通过
rb
或什么吗?你不应该犯那个错误。不过,它不会创建您期望的文件名。相反,您应该在enumerate(scidata)中迭代i的数组:nop当我发布代码时,我更改了行,但现在我有一个不同的错误:Indexer错误:元组索引超出范围如果没有数据文件,则无法调试当前代码。你能直接在代码中创建一个小的3d数组吗?这将允许我们解决您的编码问题,然后您可以处理读取您的文件。或者。将您的数据文件发布到公共位置,并在问题中包含URL。不幸的是,我不能,数据来自fits数据立方体,我提取了其中一个表数据,行为:scidata=data[0]。data,是否需要将其上载到某个位置?我将数组的一部分放在代码中以显示其结构;实际上,我可以在一个文件中写入所有数组,但这不起作用。我更改了行,但现在出现了一个不同的错误:indexer-ror:tuple-index-out-of-ofrange@JavierSuarezscidata的形状是什么?它是(766L,256L,256L)
for idx, slice in enumerate(scidata):
    # code follows