[英]Replace dataframe header with lines of string
I have a pandas dataframe that looks like this: 我有一个看起来像这样的熊猫数据框:
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
How can I write the data to a .csv (or .txt) file without row indices, so that the columns are tab (or space) delimited, and the header is displayed as follows: 如何将数据写入没有行索引的.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
FYI: The header is Tecplot software header. 仅供参考:标头是Tecplot软件标头。
(I haven't tested this personally, so there may need some tweaks ;-)) According to the Panda docs, something like this should work: https://pandas.pydata.org/pandas-docs/stable/io.html#io-store-in-csv (我还没有亲自测试过,所以可能需要一些调整;-))根据熊猫文档,类似的东西应该可以工作: 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+')
Prepare your inputs: 准备您的输入:
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']])
To save to Excel file: 要保存到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()
To save to CSV file: 要保存到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=' ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.