处理带双引号和数字的混合字符串以保存在csv中

时间:2018-03-03 00:43:25

标签: python pandas csv dataframe

我有三行需要保存为我的csv文件的标题。他们应该是这样的:

title = "dataset test"
variables = "X", "Y", "Z", "V"
zone t = "Data Field", i = 134, j = 293, k = 5, f=point

我使用以下代码创建pandas数据帧:

info = pd.DataFrame(['title = "dataset test"',
                    'variables = "X", "Y", "Z", "V"',
                    'zone t = "Data Field", i = 134, j = 293, k = 5, f=point'])

使用以下代码编写csv文件:

with open(fpath, 'w') as myfile:
        info.to_csv(myfile, header=None, index=False)

然而,csv文件中的输出为:

"title = ""dataset test"""
"variables = ""X"", ""Y"", ""Z"", ""V"""
"zone t = ""Data Field"", i = 134, j = 293, k = 5, f=point"

在此标题下方有三列数字,之后将添加;最终的输出应该是这样的:

title = "dataset test"
variables = "X", "Y", "Z", "V"
zone t = "Data Field", i = 134, j = 293, k = 5, f=point
6.1961335E+06   2.3218804E+06   1.3564390E+03
6.1961547E+06   2.3218672E+06   1.3473630E+03
6.1961759E+06   2.3218540E+06   1.3382290E+03
6.1961972E+06   2.3218408E+06   1.3322720E+03

我使用df.to_csv(myfile, header=None, index=False, sep='\t',float_format='%.7E')

执行此操作

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用此行中的\转义字符

'variables = "X", "Y", "Z", "V"'

喜欢这个

'variables = \"X\", \"Y\", \"Z\", \"V\"'