[英]How can I get a pandas dataframe into CSV format with different formats per columns?
Issues for pandas' DataFrame text output functions:熊猫 DataFrame 文本 output 函数的问题:
What I do so far:到目前为止我做了什么:
I generate a list of formatting strings in the new Python formatting format, so eg ['{8.1f}','{9.3f}',...,]
, and then do this hack:我以新的 Python 格式化格式生成格式化字符串列表,例如['{8.1f}','{9.3f}',...,]
,然后执行以下操作:
f.write(', '.join(fmt).format(*data)+'\r\n')
Is there a way I can have pandas do some of this hacking for me or is that a feature request and I already did all the work?有没有办法让 pandas 为我做一些黑客攻击,或者这是一个功能请求,我已经完成了所有工作? ;) ;)
np.savetxt
can do it (by supplying fmt
argument, which can be a list
), but that means the column names has to be written separately ( header
argument): np.savetxt
可以做到(通过提供fmt
参数,它可以是一个list
),但这意味着必须单独编写列名( header
参数):
np.savetxt('temp.csv', df.values, fmt=['%8.1f','%9.3f','%8.1f','%9.3f','%8.1f'],
delimiter=',', header=' '+' ,'.join(df.columns), comments='')
You can try this:你可以试试这个:
import pandas as pd
df = pd.DataFrame({
'a': [-8.114445, 888.303217, 80],
'b': ['d', 'gg5g', '9ghhhh'],
'c': [14.34e+4,12.1e-1,1e-5],
'd': [34,65373,-176576]}
)
df.to_string("temp.txt",
formatters={
"a": "{:6,.2f}".format,
"b": "{:<}".format,
"c": "{:9,.5e}".format,
"d": "{:7d}".format
}, index=False
)
Content of "temp.txt": “temp.txt”的内容:
a b c d
-8.11 d 1.43400e+05 34
888.30 gg5g 1.21000e+00 65373
80.00 9ghhhh 1.00000e-05 -176576
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.