我有一个像这样的pandas数据框:
X Y Z Value
0 6.196133e+06 2.321880e+06 1356.439 0.01
1 6.196155e+06 2.321867e+06 1347.363 0.01
2 6.196176e+06 2.321854e+06 1338.229 0.01
3 6.196197e+06 2.321841e+06 1332.272 0.01
4 6.196218e+06 2.321828e+06 1326.691 0.01
如何在没有行索引的情况下将数据写入.csv(或.txt)文件,以便列以制表符(或空格)分隔,并且标题显示如下:
title = "dataset test"
variables = "X", "Y", "Z", "Value"
zone t = "Data Field",i = 134, j = 293, k = 5, f=point
6.196133e+06 2.321880e+06 1356.439 0.01
6.196155e+06 2.321867e+06 1347.363 0.01
6.196176e+06 2.321854e+06 1338.229 0.01
6.196197e+06 2.321841e+06 1332.272 0.01
6.196218e+06 2.321828e+06 1326.691 0.01
仅供参考:标题是Tecplot软件标题。
答案 0 :(得分:1)
(我还没有亲自测试过,所以可能需要一些调整;-)) 根据熊猫文档,这样的事情应该有效:https://pandas.pydata.org/pandas-docs/stable/io.html#io-store-in-csv
filename = 'output.csv'
with open(filename, 'w') as fid:
# write the Tecplot header
fid.write('title = "dataset test"')
fid.write('variables = [{0}]'.format(df.columns))
fid.write('zone t = "Data Field",i = 134, j = 293, k = 5, f=point')
# write the data
df.to_csv(filename, '\t', columns=df.columns, header=False, index=False, mode='w+')
答案 1 :(得分:1)
准备你的输入:
import pandas as pd
import os
os.chdir('Directory to save to')
df = pd.DataFrame([[6.196133e+06,2.321880e+06,1356.439,0.01],
[6.196155e+06,2.321867e+06,1347.363,0.01],
[6.196176e+06,2.321854e+06,1338.229,0.01],
[6.196197e+06,2.321841e+06,1332.272,0.01],
[6.196218e+06,2.321828e+06,1326.691,0.01]],columns = ['X','Y','Z','Value'])
info = pd.DataFrame([['title = "dataset test"'],
['variables = ' + str(df.columns.tolist())],
['zone t = "Data Field", i = 134, j = 293, k = 5, f=point']])
要保存到Excel文件:
writer = pd.ExcelWriter('out.xlsx', engine='openpyxl')
info.to_excel(writer, sheet_name='Output', header=None, index=False, startcol=0,startrow=0)
df.to_excel(writer, sheet_name='Output', header=None, index=False, startcol=0,startrow=3)
writer.save()
要保存到CSV文件:
with open('out.csv', 'w') as myfile:
info.to_csv(myfile, header=None, index=False, sep=' ')
df.to_csv(myfile, header=None, index=False, sep=' ')