如何在 pandas to_csv()中设置自定义分隔符? [英] How to set a custom separator in pandas to_csv()?

查看:2135
本文介绍了如何在 pandas to_csv()中设置自定义分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从文档中我知道,要保存为.csv文件,可以简单地做到:

From the docs I know that in order to save as a .csv file one can simply do:

df.to_csv(sep = ';')

但是,我想使用我的自定义分隔符,例如::::.如何将:::设置为分隔符?我试图:

However, I would like to use my custom separator, for instance: :::. How can I set ::: as a separator?. I tried to:

df.to_csv(sep = ':::')

得到了:TypeError: "delimiter" must be a 1-character string

我也尝试:df.to_csv('../data.csv', sep='\s*\:::', index=False),并得到了相同的结果.因此,如何设置自己的分隔符?

Also I tried to: df.to_csv('../data.csv', sep='\s*\:::', index=False), and got the same result. Thus, How can I set my own separator?.

更新

由于我的数据框为|,因此不能使用此类字符作为分隔符.我尝试使用以下方法将其删除:

Since I have in my dataframe |, I can not use such character as a separator. I tried to removed it with:

df.replace('\b|\b', '-', regex = True)

但是,它没有用.关于如何删除它的其他选择吗?.

However, it did not worked. Any alternative on how to remove it?.

推荐答案

很明显,熊猫似乎不允许这种行为.

Obviously Pandas seems not to allow this behavior.

但是,如果您绝对希望使用":::".为什么不导出带有不常见字符(例如"|")的数据框然后打开文件并替换为"|"通过":::".

However, if you absolutely want ":::". Why not exporting the dataframe with an uncommon character such as "|" and then open back the file and replace "|" by ":::".

那是我想象中能达到预期效果的唯一解决方案.

That's the only solution I imagine to perform your desired result.

这篇关于如何在 pandas to_csv()中设置自定义分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆