从3D数组中写入多个文件

时间:2017-04-21 21:03:03

标签: python arrays file numpy numpy-ndarray

我有一个形状为的3D数组:(766L,256L,256L),我需要为数组中的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='====')

但是在runnig之后我得到了下一个错误,(我在编辑后编辑,第一个错误消失但现在显示出来):

ncol = X.shape[1]

IndexError: tuple index out of range

1 个答案:

答案 0 :(得分:0)

问题在于:

for i in scidata:

上面的循环每次都会给你一个766个切片,而不是你在创建.csv文件时使用的索引。

因此,将该行更改为

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

或者如评论中所述,使用:

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