Say I have population data stored in a column of a dataframe using pandas in python with Country names as row indices. How do I convert the whole column of numbers into string thousands separator using commas. Basically, I need 12345678,integer, converted into 12,345,678.
Add Thousand Comma Separators We use the python string format syntax '{:,. 0f}'. format to add the thousand comma separators to the numbers. Then we use python's map() function to iterate and apply the formatting to all the rows in the 'Median Sales Price' column.
Convert All Columns to Strings If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df. astype(str) methods.
Using apply
to format the numbers.
In [40]: ps.apply('{:,}'.format)
Out[40]:
CountryA 12,345,678
CountryB 3,242,342
dtype: object
In [41]: ps
Out[41]:
CountryA 12345678
CountryB 3242342
dtype: int64
You can use regex as well.
df['Population'].str.replace(r"(?!^)(?=(?:\d{3})+$)", ",")
See demo.
https://regex101.com/r/cVYAGw/1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With