Python/Pandas: Converting numbers by comma separated for thousands

我怕爱的太早我们不能终老 提交于 2021-02-08 13:45:24

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/46677550/python-pandas-converting-numbers-by-comma-separated-for-thousands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!