简体   繁体   English

Python Pandas - 写入 to_csv 时使用多字符分隔符

[英]Python Pandas - use Multiple Character Delimiter when writing to_csv

It appears that the pandas to_csv function only allows single character delimiters/separators.看来熊猫 to_csv 函数只允许单字符分隔符/分隔符。

Is there some way to allow for a string of characters to be used like, "::" or "%%" instead?有没有办法允许使用字符串,例如“::”或“%%”?

I tried:我试过:

df.to_csv(local_file,  sep = '::', header=None, index=False)

and getting:并获得:

TypeError: "delimiter" must be a 1-character string

Use numpy-savetxt使用numpy-savetxt

Ex:前任:

np.savetxt(file.csv, np.char.decode(chunk_data.values.astype(np.bytes_), 'UTF-8'), delimiter='~|', fmt='%s',encoding=None)

np.savetxt(file.dat, chunk_data.values, delimiter='~|', fmt='%s',encoding='utf-8')

Think about what this line a::b::c' means to a standard CSV tool: an a , an empty column, a b , an empty column, and a c .想想这一行a::b::c'对标准 CSV 工具意味着什么:一个a 、一个空列、一个b 、一个空列和一个c Even in a more complicated case with quoting or escaping: "abc::def"::2 means an abc::def , an empty column, and a 2.即使在更复杂的引用或转义情况下: "abc::def"::2表示 a abc::def 、一个空列和一个 2。

So, all you have to do is add an empty column between every column, and then use : as a delimiter, and the output will be almost what you want.所以,你所要做的就是在每列之间添加一个空列,然后使用:作为分隔符,输出将几乎是你想要的。

I say “almost” because Pandas is going to quote or escape single colons.我说“几乎”是因为 Pandas 会引用或转义单个冒号。 Depending on the dialect options you're using, and the tool you're trying to interact with, this may or may not be a problem.根据您使用的方言选项以及您尝试与之交互的工具,这可能是也可能不是问题。 Unnecessary quoting usually isn't a problem (unless you ask for QUOTE_ALL , because then your columns will be separated by :"": , so hopefully you don't need that dialect option), but unnecessary escapes might be (eg, you might end up with every single : in a string turned into a \\: or something).不必要的引用通常不是问题(除非你要求QUOTE_ALL ,因为那样你的列将被:"":分隔,所以希望你不需要那个方言选项),但不必要的转义可能是(例如,你可能以字符串中的每个:结尾都变成了\\:或其他东西)。 So you have to be careful with the options.所以你必须小心选择。 But it'll work for the basic “quote as needed, with mostly standard other options” settings.但它适用于基本的“按需报价,主要是标准的其他选项”设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM