pandas 将pandas中各个字段的小数位数指定为csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40618092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specifying number of decimal places for individual fields in pandas to csv
提问by Carrie Brown
I am using pandas to_csv function, and want to specify the number of decimal places for float numbers. However, I want this to change based on the field.
我正在使用 pandas to_csv 函数,并且想要指定浮点数的小数位数。但是,我希望根据该领域进行更改。
For example:
例如:
my data set looks like this:
我的数据集如下所示:
sampleID Call X Y
1234 0.1234 0.123 0.123
I want the Call column to always have 4 decimal places and X and Y to always have 3.
我希望 Call 列始终有 4 个小数位,而 X 和 Y 始终有 3 个小数位。
Originally, I would use the float_format argument in to_csv, but that only appears applicable if all floats are treated the same way. How would I go about specifying the number of digits for individual columns?
最初,我会在 to_csv 中使用 float_format 参数,但这仅在所有浮点数都以相同方式处理时才适用。我将如何指定各个列的位数?
回答by Waylon Walker
You can round the columns before saving as a CSV. If you need the precision you can copy the DataFrame to retain precision in the original DataFrame.
您可以在保存为 CSV 之前对列进行四舍五入。如果您需要精度,您可以复制 DataFrame 以保留原始 DataFrame 中的精度。
df['X'] = df['X'].round(3)
df['Y'] = df['Y'].round(3)
df.to_csv('file.csv')