从 pandas 数据框中写入.csv文件,并使用连续的空格作为定界符 [英] Write .csv file from pandas dataframe with consecutive spaces as delimiter

查看:300
本文介绍了从 pandas 数据框中写入.csv文件,并使用连续的空格作为定界符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个用四个空格而不是一个制表符分隔的文本文件:

I want to write a text file which is separated by four spaces instead of one tab:

df.to_csv(file,sep= '\s\s\s\s') 

代替

df.to_csv(file,sep= '\t')

我尝试了正则表达式:

df.to_csv(file,sep= r'\s{4}') 

哪个也不起作用?

在不编写和替换定界符的情况下可以做到吗?

Is this doable without writing and the replacing the delimiter?

推荐答案

这可能是一种解决方法:

This could be a workaround:

myCsv = df.astype(str).apply(lambda x: '   '.join(x), axis=1)
myCsv.rename('   '.join(df.columns)).to_csv(file, header=True, index=False)

这篇关于从 pandas 数据框中写入.csv文件,并使用连续的空格作为定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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