How to save a whole pandas dataframe in text file
12,584
Use to_csv
with the sep='\t'
attribute.
df.to_csv('example.txt', sep='\t')
Author by
Jeanne
Updated on June 04, 2022Comments
-
Jeanne almost 2 years
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
-
cs95 over 6 years
np.savetxt('example.txt', df.values)
-
Jeanne over 6 years@cᴏʟᴅsᴘᴇᴇᴅ, I need to save it with rows and columns name, for this reason, I transform it to string
-
cs95 over 6 yearsIn that case, use
df.to_csv('example.txt', sep='\t')
-
cs95 over 6 yearsI have no idea what you're trying to do or why... Which is the line on which you get the error?
-
Jeanne over 6 years@cᴏʟᴅsᴘᴇᴇᴅ, I added some description
-
-
Aown Muhammad about 6 yearsI have tried this, but it does not save all data. Don't know why.