How to Convert Currency Strings to Floats in Pandas: Quick Methods
This article demonstrates several practical techniques for stripping dollar signs and commas from string columns in a pandas DataFrame and converting the cleaned values to floating‑point numbers, using plain Python, regular expressions, and pandas‑specific string methods.
Rescuing pandas (7) – Converting String Columns with Currency Symbols to Float
Data Requirement
The data frame contains a price column with strings like "$1,234.56" (no NaN). The task is to remove the dollar sign $ and commas , and convert the column to float.
Requirement Breakdown
Several common pandas approaches are presented for this cleaning task.
Solution
Method One
Before using pandas, you can rely on Python built‑ins and the re module.
Using two str.replace calls
# Using two string.replace methods
data['price'] = [float(i.replace('$', '').replace(',', '')) for i in data['price']]Using the re module
# re
import re
data['price'] = [float(re.sub(r'[$,]', '', i)) for i in data['price']]The result is the same as above.
Method Two
Leverage pandas methods such as .map and .str operations.
Map with lambda and
replace # Using map with chained replace
data['price'].map(lambda x: x.replace('$', '').replace(',', '')).astype(float)Map with
re.sub # Using map with re
data['price'].map(lambda x: re.sub(r'[$,]', '', x)).astype(float)Split and join after stripping
# Join after split and strip
data['price'].map(lambda x: ''.join(x.lstrip('$').split(','))).astype(float)Using pandas .str.split and
.str.strip# .str.strip().str.split() then join
data['price'].str.strip('$').str.split(',').map(lambda x: ''.join(x)).astype(float)Direct .str.replace with regex
# .str.replace with regex
data['price'].str.replace(r'[$,]', '', regex=True).astype(float)Summary
Different approaches can achieve the same goal; choose the one that fits your coding style. While pandas offers concise .str.replace, other methods using Python built‑ins or re are also viable. This short guide lists several easy‑to‑understand solutions for cleaning currency strings in pandas.
Spring snow enters the white grassland, a lone bird wanders.
Written on February 12, 2022
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
