我很难让熊猫dataframe.to_csv(...)
的输出正确引用字符串。
import pandas as pd
text = 'this is "out text"'
df = pd.DataFrame(index=['1'],columns=['1','2'])
df.loc['1','1']=123
df.loc['1','2']=text
df.to_csv('foo.txt',index=False,header=False)
产出如下:
123,“这是”外文“
但我想:
123,这是“外文”
有人知道怎么把这事做好吗?
发布于 2014-01-15 20:11:09
例如,您可以通过quoting=csv.QUOTE_NONE
:
>>> df.to_csv('foo.txt',index=False,header=False)
>>> !cat foo.txt
123,"this is ""out text"""
>>> import csv
>>> df.to_csv('foo.txt',index=False,header=False, quoting=csv.QUOTE_NONE)
>>> !cat foo.txt
123,this is "out text"
但根据我的经验,最好多引用,而不是少引用。
发布于 2015-07-02 22:03:14
注意:目前Pandas string documentation中有一个小错误。上面写着:
但这改变了csv定义QUOTE_NONE和QUOTE_NONNUMERIC变量的方式。
In [13]: import csv
In [14]: csv.QUOTE_NONE
Out[14]: 3
发布于 2018-08-21 05:06:30
要使用quoting=csv.QUOTE_NONE
,您需要设置escapechar
。
# Create a tab-separated file with quotes
$ echo abc$'\t'defg$'\t'$'"xyz"' > in.tsv
$ cat in.tsv
abc defg "xyz"
# Gotcha the quotes disappears in `"..."`
$ python3
>>> import pandas as pd
>>> import csv
>>> df = pd.read("in.tsv", sep="\t")
>>> df = pd.read_csv("in.tsv", sep="\t")
>>> df
Empty DataFrame
Columns: [abc, defg, xyz]
Index: []
# When reading in pandas, to read the `"..."` quotes,
# you have to explicitly say there's no `quotechar`
>>> df = pd.read_csv("in.tsv", sep="\t", quotechar='\0')
>>> df
Empty DataFrame
Columns: [abc, defg, "xyz"]
Index: []
# To print out without the quotes.
>> df.to_csv("out.tsv", , sep="\t", quoting=csv.QUOTE_NONE, quotechar="", escapechar="\\")
https://stackoverflow.com/questions/21147058
复制相似问题