如何在文本文件中保存整个pandas数据帧

时间:2017-10-19 00:18:23

标签: python pandas formatting

这是我的代码,用于将一些带有描述的pandas数据帧保存到文本文件中:

    import numy as np
    import pandas as pd
    rows=['row1','row2','row3', 'row4']
    data=np.random.randn(18, 4,3)
    with open(filename, "wb") as outfile:
         house_num = 0
         outfile.write(('Shape of house Array: {0}    \n'.format(data.shape)).encode())
         for data_slice in data:
             outfile.write(('@ House: {0} \n'.format(house_num)).encode())
             df=pd.DataFrame(data_slice,columns=list('XYZ'),dtype=float)
             df=df.rename(index={j:k for k, j in zip(rows,range(0,4))})
             text=df.to_string()
             np.savetxt(filename, text)
             house_num+=1

在最后一行,我收到错误IndexError: tuple index out of range

我希望获得这样的文本文件格式:

Shape of house Array: (18,4,3)
house: 0
             X         Y         Z
row1  1.376328  0.620332 -0.726298
row2 -0.671292  0.557585 -0.027483
row3  0.381491  1.798442  0.221806
row4 -0.223592 -0.297638 -0.258627
house: 1
             X         Y         Z
row1  1.376328  0.620332 -0.726298
row2 -0.671292  0.557585 -0.027483
row3  0.381491  1.798442  0.221806
row4 -0.223592 -0.297638 -0.258627
....

house: 18
             X         Y         Z
row1  1.376328  0.620332 -0.726298
row2 -0.671292  0.557585 -0.027483
row3  0.381491  1.798442  0.221806
row4 -0.223592 -0.297638 -0.258627

2 个答案:

答案 0 :(得分:2)

to_csvsep='\t'属性一起使用。

df.to_csv('example.txt', sep='\t')

答案 1 :(得分:0)

import numpy as np
import pandas as pd
rows=['row1','row2','row3', 'row4']
data=np.random.randn(3, 4,3)
with open(filename, "wb") as outfile:
     house_num = 0
     outfile.write(('Shape of house Array: {0}    \n'.format(data.shape)).encode())
     for data_slice in data:
         outfile.write(('@ House: {0} \n'.format(house_num)).encode())
         df=pd.DataFrame(data_slice,columns=list('XYZ'),dtype=float)
         df=df.rename(index={j:k for k, j in zip(rows,range(0,4))})
         text=df.to_string()
         #np.savetxt(filename, text)
         outfile.write(text.encode())
         outfile.write(("\n").encode())
         house_num+=1

输出文字文件:

Shape of house Array: (3, 4, 3)    
@ House: 0 
             X         Y         Z
row1  2.839710 -0.577583  0.763323
row2 -0.419653  0.700541  0.169561
row3 -0.368513  1.255395 -0.790997
row4  0.731944 -3.038690 -2.134272
@ House: 1 
             X         Y         Z
row1  0.464832  0.207018  1.067246
row2 -0.216544 -0.141985 -1.895549
row3 -1.116220  0.887194  1.139350
row4  1.010944 -0.271821 -0.222212
@ House: 2 
             X         Y         Z
row1 -0.768003 -0.308128 -1.613605
row2  0.144122 -0.024041 -0.495055
row3  0.004526 -1.789065 -1.286156
row4  1.310501 -0.821195  1.006570