0

I need to convert French formatted numbers extracted from .csv into English formatted numbers so I can use dataframe functions. The .csv gives:

              Beta         Alpha
2014-07-31     100           100
2014-08-01   99,55  100,01336806
2014-08-04   99,33  100,05348297
2014-08-05   99,63  100,06685818
2014-08-06   98,91  100,08023518

"99,5" & "100,01336806" are actually objects for python. I need to turn them into floats with the following format "99.5" and "100.01336806"

I tried: df = df.str.replace(to_replace =',', value = '.', case = False) Doesn't give my any error for that code line but doesn't switch the ',' into '.' either.

df = pd.to_numeric(df, error = 'coerce') TypeError: arg must be a list, tuple, 1-d array, or Series

Also tried the regex module without success, and I would rather use built-in function if possible.

Any help welcome!

JoeBadAss
  • 49
  • 10
  • 2
    Ha, I thought this was about converting "quatre-vingt-dix-huit" to "ninety-eight" :-P (I don't have an idea for a better title, though) – superb rain Sep 24 '20 at 11:08
  • Check this answer it has a format example https://stackoverflow.com/a/19798528/652528 – geckos Sep 24 '20 at 11:20
  • Have you tried with functions from the [`locale` module from the standard library](https://docs.python.org/3/library/locale.html#locale.atof)? – Stef Dec 28 '21 at 22:59

2 Answers2

1

What is the type of sources objects are "99,5" & "100,01336806", and what type of target objects do you want ? The following tested with Python 3.8

Case 1: source object is numeric, target is string. Formatting do not allow "French format", only "English". So have to substitute . and ,

Eg. (float) 99.55 -> (string) '99,55'

v1 = float(99.55)
f"{v1:,.2f}"
'99.55'
f"{v1:,.2f}".replace(".",",")
'99,55'

Case 2: source is string with "English" format, target is float. Means the , must be replaced by a . first before converting the string to float

Eg. (string) '99,55' -> (float) 99.55

v2 = "99,55"
float(v2.replace(",","."))
99.55
0

try using the replace() function.

x = "100,01336806"
y = x.replace(",",".")
print(y)
  • Unfortunately, like when the `df.str.replace` was used, it doesn't give any error message for that specific code line and does not switch "," into "." either. Thanks anyway :) @coder3332 – JoeBadAss Sep 24 '20 at 13:03