Convert string to Float with dot and also comma
Question:
This is the column of a dataframe that I have (values are str):
Values
7257.5679
6942.0949714286
5780.0125476250005
This is how I want the record to go to the database:
Values
7.257,56
6.942,09
5.780,01
How can I do this? Thanks in advance!
Answers:
df["Values"] = df["Values"].apply(lambda x: "{:,.2f}".format(float(x)))
Output:
Values
0 7,257.57
1 6,942.09
2 5,780.01
To get values
in the format 7.257,56
. You can make good use of the replace
function:
df["Values"] = df["Values"].apply(lambda x: "{:,.2f}".format(float(x)).replace(".", ",").replace(",", ".", 1))
But replace
might not be more efficient and concise when dealing with larger dataset, in that case you might want to look into translate
, that will be the best approach to go with.
trans_column = str.maketrans(",.", ".,")
df["Values"] = df["Values"].apply(lambda x: "{:,.2f}".format(float(x)).translate(trans_column))
Output:
Values
0 7.257,57
1 6.942,09
2 5.780,01
This is the column of a dataframe that I have (values are str):
Values |
---|
7257.5679 |
6942.0949714286 |
5780.0125476250005 |
This is how I want the record to go to the database:
Values |
---|
7.257,56 |
6.942,09 |
5.780,01 |
How can I do this? Thanks in advance!
df["Values"] = df["Values"].apply(lambda x: "{:,.2f}".format(float(x)))
Output:
Values
0 7,257.57
1 6,942.09
2 5,780.01
To get values
in the format 7.257,56
. You can make good use of the replace
function:
df["Values"] = df["Values"].apply(lambda x: "{:,.2f}".format(float(x)).replace(".", ",").replace(",", ".", 1))
But replace
might not be more efficient and concise when dealing with larger dataset, in that case you might want to look into translate
, that will be the best approach to go with.
trans_column = str.maketrans(",.", ".,")
df["Values"] = df["Values"].apply(lambda x: "{:,.2f}".format(float(x)).translate(trans_column))
Output:
Values
0 7.257,57
1 6.942,09
2 5.780,01