Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Pandas: Converting numbers by comma separated for thousands

I have a dataframe with a column containing long numbers. I am trying to convert all the values in the numbers column to comma separated for thousands.

df

col_1      col_2
Rooney     34590927
Ronaldo    5467382
John       25647398

How do I iterate and get the following result?
Expected result:

col_1      col_2
Rooney     34,590,927
Ronaldo    5,467,382
John       25,647,398
like image 376
Preetesh Gaitonde Avatar asked Oct 10 '17 23:10

Preetesh Gaitonde


People also ask

How do I set a thousand separator in pandas?

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 Split comma Separated values in pandas DataFrame?

Split column by delimiter into multiple columns Apply the pandas series str. split() function on the “Address” column and pass the delimiter (comma in this case) on which you want to split the column. Also, make sure to pass True to the expand parameter.


2 Answers

You can use string formatting,

df['col_2'] = pd.to_numeric(df['col_2'].fillna(0), errors='coerce')    
df['col_2'] = df['col_2'].map('{:,.2f}'.format)

Do remember that the col_2 now will be string not integer.

    col_1   col_2
0   Rooney  34,590,927.00
1   Ronaldo 5,467,382.00
2   John    25,647,398.00
like image 73
Vaishali Avatar answered Nov 03 '22 00:11

Vaishali


apply format function to col_2

df = df.assign(col_2=df.col_2.astype(int).apply('{:,}'.format))

     col_1       col_2
0   Rooney  34,590,927
1  Ronaldo   5,467,382
2     John  25,647,398
like image 29
galaxyan Avatar answered Nov 03 '22 00:11

galaxyan