# Convert number strings with commas in pandas DataFrame to float

StackOverflow

I have a DataFrame that contains numbers as strings with commas for the thousands marker. I need to convert them to floats.

``````a = [["1,200", "4,200"], ["7,000", "-0.03"], [ "5", "0"]]
df=pandas.DataFrame(a)
``````

I am guessing I need to use locale.atof. Indeed

``````df.apply(locale.atof)
``````

works as expected. I get a Series of floats.

But when I apply it to the DataFrame, I get an error.

``````df.apply(locale.atof)
``````

TypeError: ("cannot convert the series to ", u"occurred at index 0")

and

``````df[0:1].apply(locale.atof)
``````

gives another error:

ValueError: ("invalid literal for float(): 1,200", u"occurred at index 0")

So, how do I convert this `DataFrame` of strings to a DataFrame of floats?

If you"re reading in from csv then you can use the thousands arg:

``````df.read_csv("foo.tsv", sep="	", thousands=",")
``````

This method is likely to be more efficient than performing the operation as a separate step.

You need to set the locale first:

``````In [ 9]: import locale

In : from locale import atof

In : locale.setlocale(locale.LC_NUMERIC, "")
Out: "en_GB.UTF-8"

In : df.applymap(atof)
Out:
0        1
0  1200  4200.00
1  7000    -0.03
2     5     0.00
``````
{"ft_lang_label":"__label__en","ft_lang_prob":0.83661026,"math_prob":0.7815122,"size":1965,"snap":"2021-43-2021-49","text_gpt3_token_len":512,"char_repetition_ratio":0.09127996,"word_repetition_ratio":0.0,"special_character_ratio":0.297201,"punctuation_ratio":0.19158879,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9873875,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-12-03T12:43:46Z\",\"WARC-Record-ID\":\"<urn:uuid:0235483d-97f9-4c92-8e54-44263a5fb421>\",\"Content-Length\":\"31289\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:dfdd389a-81d1-4ae8-9686-16c92cd4ecaf>\",\"WARC-Concurrent-To\":\"<urn:uuid:568b27a4-dc72-44ec-bc1d-4e68a6d204e0>\",\"WARC-IP-Address\":\"172.67.181.212\",\"WARC-Target-URI\":\"https://python.engineering/22137723-convert-number-strings-with-commas-in-pandas-dataframe-to-float/\",\"WARC-Payload-Digest\":\"sha1:R3QHADXWRYLJEWYYCHKWW4MIQCGZX3BQ\",\"WARC-Block-Digest\":\"sha1:SYVEMLSVUGOHZDKLCSK4TF3L5QQ2PQOS\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-49/CC-MAIN-2021-49_segments_1637964362879.45_warc_CC-MAIN-20211203121459-20211203151459-00318.warc.gz\"}"}