Reputation: 1331
Here is my code to save several pandas dataframe with some description into a text file:
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
in the last line , I get an error IndexError: tuple index out of range
I want to get a text file formatting like this:
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
Upvotes: 2
Views: 15134
Reputation: 1331
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
Output text file:
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
Upvotes: 0
Reputation: 10083
Use to_csv
with the sep='\t'
attribute.
df.to_csv('example.txt', sep='\t')
Upvotes: 7