Python,Pandas:将DataFrame的内容写入文本File

时间:2022-04-17 22:51:07

I have pandas DataFrame like this

我有像这样的pandas DataFrame

        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 in this way,

我想以这种方式将这些数据写入文本文件,

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 its not working. how to do this?

但它不起作用。这个怎么做?

3 个解决方案

#1


50  

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

您可以使用np.savetxt并访问np属性.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:

或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.

请注意,对于np.savetxt,您必须传递一个使用追加模式创建的文件句柄。

#2


14  

You can use pandas.DataFrame.to_csv(), and setting both index and header to False:

您可以使用pandas.DataFrame.to_csv(),并将索引和标头设置为False:

In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

pandas.DataFrame.to_csv can write to a file directly, for more info you can refer to the docs linked above.

pandas.DataFrame.to_csv可以直接写入文件,有关详细信息,请参阅上面链接的文档。

#3


5  

Late to the party: Try this>

晚到派对:试试这个>

#pd: your pandas dataframe
base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
    pd.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file

#1


50  

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

您可以使用np.savetxt并访问np属性.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:

或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.

请注意,对于np.savetxt,您必须传递一个使用追加模式创建的文件句柄。

#2


14  

You can use pandas.DataFrame.to_csv(), and setting both index and header to False:

您可以使用pandas.DataFrame.to_csv(),并将索引和标头设置为False:

In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

pandas.DataFrame.to_csv can write to a file directly, for more info you can refer to the docs linked above.

pandas.DataFrame.to_csv可以直接写入文件,有关详细信息,请参阅上面链接的文档。

#3


5  

Late to the party: Try this>

晚到派对:试试这个>

#pd: your pandas dataframe
base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
    pd.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file