Reputation: 403
How can I write a CSV file in Python with comma as a decimal separator? This problem looks simple, but I've been spending many hours today and can't solve it (googleing, search here in stackoverflow...).
This doesn't work:
file.to_csv('file.csv', index = False, sep = ";", float_format = ",")
In output csv still have ".".
Thank you for your answer.
Upvotes: 3
Views: 12571
Reputation: 1
I had the same problem and fixed it by changing the data format for the dataframe to numeric.
with pd.ExcelWriter('OLS_results.xlsx', engine='xlsxwriter') as writer:
df1 = df1.apply(pd.to_numeric, errors='ignore')
df1.to_excel(writer)
Upvotes: 0
Reputation: 1054
You can save with commma directly using decimal= ","
.
This is especified in pandas.DataFrame.to_csv() documentation.
The following code should work:
file.to_csv('file.csv', index = False, sep = ";", decimal= ",")
Upvotes: 5
Reputation: 403
My solution:
import pandas as pd
import numpy as np
data = pd.read_csv(r'data.csv', decimal = ',')
dims = data.columns[0:3]
metrics = data.columns[3:]
dims = data[dims].copy()
metrics = data[dims].copy()
dtypes=np.dtype([
('col1',str),
('col2',str),
('col3',str),
('col4',int),
('col5',int)])
dataf = np.empty(0,dtype=dtypes)
df = pd.DataFrame(dataf)
data = pd.DataFrame({
"col1": dims["col1"],
"col2": dims["col2"],
"col3": dims["col3"],
"col4": dims["col4"],
"col4": dims["col4"]})
df = df.append(data)
df[['col1',
'col2',
'col3']] = df[['col1',
'col2',
'col3']].replace('\;', ',', regex = True)
df[['col4',
'col5']] = df[['col4',
'col5']].replace('\.', ',', regex = True)
df = df.applymap(str)
df.to_csv('new_file.csv', index = False)
Upvotes: 1
Reputation: 3794
You can take advantage of the pandas to_csv method and use the decimal parameter to designate the comman "," as decimal separator.
EDIT
Given the following code you posted the following should work:
import pandas as pd
data = pd.read_csv(r'file.csv', sep = ',', decimal = '.')
data.to_csv('foo.csv', decimal = ',', sep = ';', index = False)
Upvotes: 1
Reputation: 403
My code (I need only read csv with decimas as "." and save with ","):
import pandas as pd
file = pd.read_csv(r'file.csv', decimal = ',')
file = file.copy().replace(".", ",")
file.to_csv('file_updated.csv', index = False, sep = ";", decimal = ",")
Upvotes: 0