[英]Python pandas preserving decimal commas in the output csv file
I'm using pandas library to do some operations on .csv
file.我正在使用 pandas 库对
.csv
文件进行一些操作。
Input file input.csv
:输入文件
input.csv
:
A B
1,2 2,2
3,5 5,4
My code:我的代码:
import pandas as pd
df = read_csv('input.csv', sep = ';', encoding = 'ANSI', decimal = ',')
'''
some operations on cells like adding, multiplying...
'''
df.to_csv('output.csv', sep = ';', encoding = 'ANSI', index = False)
And here is how my output.csv
looks like:这是我的
output.csv
样子:
A B C
1.2 2.2 6.5
3.5 5.4 7.8
But is there any way to keep my decimal separator as comma like there was in the input.csv
?但是有没有办法让我的小数点分隔符像
input.csv
中的逗号一样?
Here is how output.csv
should look like:以下是
output.csv
的外观:
A B C
1,2 2,2 6,5
3,5 5,4 7,8
I have tried something like this but it didn't work:我尝试过这样的事情,但没有奏效:
df = df.astype(str).replace('.',',')
Method 1方法一
You can use:您可以使用:
df.to_csv('output.csv', sep = ';', encoding='ANSI', index=False, decimal=",")
Method 2方法二
As an alternative you can also use.作为替代方案,您也可以使用。
df = df.applymap(lambda x: str(x).replace('.',','))
instead of df = df.astype(str).replace('.',',')
而不是
df = df.astype(str).replace('.',',')
It would give:它会给:
A B C
0 1,2 2,2 6,5
1 3,5 5,4 7,8
And then接着
df.to_csv('output.csv', sep = ';', encoding = 'ANSI', index=False)
与pandas.read_csv
一样, DataFrame.to_csv也有一个decimal
参数:
df.to_csv('output.csv', sep = ';', encoding='ANSI', index=False, decimal=",")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.