Python, Pandas : write content of DataFrame into text File

Sounak picture Sounak · Jul 6, 2015 · Viewed 290.3k times · Source

I have pandas DataFrame like this

        X    Y  Z    Value 
0      18   55  1      70   
1      18   55  2      67 
2      18   57  2      75     
3      18   58  1      35  
4      19   54  2      70   

I want to write this data to a text file that looks like this:

18 55 1 70   
18 55 2 67 
18 57 2 75     
18 58 1 35  
19 54 2 70 

I have tried something like

f = open(writePath, 'a')
f.writelines(['\n', str(data['X']), ' ', str(data['Y']), ' ', str(data['Z']), ' ', str(data['Value'])])
f.close()

but it's not working. How to do this?

Answer

EdChum picture EdChum · Jul 6, 2015

You can just use np.savetxt and access the np attribute .values:

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')

yields:

18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

or to_csv:

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')

Note for np.savetxt you'd have to pass a filehandle that has been created with append mode.