'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
Solution 1:[1]
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
Solution 2:[2]
d = len(list(df.columns))
i.e d=22
d = d-2 and we want to convert only 20 columns
for x in df.columns[-d:]:
df[x] = [(locale.format("%d", a, grouping=True)) for a in df[x]]
This will solve the problem and dynamically make it comma separated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | pppery |
