Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a full column of integer into string with thousands separated using comma in pandas

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.

like image 304
Uday Panta Avatar asked Dec 24 '16 15:12

Uday Panta


People also ask

How do I set a thousand separator in pandas?

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.

How do I convert a whole column to a string?

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.


2 Answers

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
like image 176
Zero Avatar answered Sep 29 '22 02:09

Zero


You can use regex as well.

df['Population'].str.replace(r"(?!^)(?=(?:\d{3})+$)", ",")

See demo.

https://regex101.com/r/cVYAGw/1

like image 25
vks Avatar answered Sep 29 '22 01:09

vks