Home >Backend Development >Python Tutorial >How to Convert Number Strings with Commas to Floats in a Pandas DataFrame?
Converting Number Strings with Commas to Float in Pandas DataFrame
Issue: Converting number strings with commas as thousand markers to float values in a pandas DataFrame.
Solution:
To convert number strings with commas to floats, follow these steps:
import locale
Set the locale to match the formatting of the number strings. For example, for English (Great Britain), use the following:
locale.setlocale(locale.LC_NUMERIC, '')
Apply the atof() function to each element in the DataFrame using applymap():
df['column_name'] = df['column_name'].applymap(locale.atof)
Alternatively, for CSV Files:
If reading the data from a CSV file, use the thousands argument in read_csv():
df = pd.read_csv('foo.csv', thousands=',')
The above is the detailed content of How to Convert Number Strings with Commas to Floats in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!