How to Format Numbers with Commas for Thousands in Pandas
To display large numbers in a more readable format we can insert commas as thousands separators in Pandas. This is especially useful when preparing data for presentation or reports.
Below is a quick solution to format numbers with commas using Pandas:
(1) Display Only
df.style.format('{:,}')
or
df.head().style.format("{:,.0f}")
(2) Format parameter for thousands char
df.style.format(thousands=",")
(3) Format multiple columns
col_format = {"sales": "{:,.0f}", "col2": "{:,.0f}"}
df.head().style.format(col_format)
(4) pandas format comma thousands
df['sales'].apply(lambda x: f"{x:,}")
Data
Suppose we have the following DataFrame:
import pandas as pd
df = pd.DataFrame({
'sales': [1000, 15000, 2500000]
})
df
data:
sales | |
---|---|
0 | 1000 |
1 | 15000 |
2 | 2500000 |
Display Commas Without Changing Values
If you only need the formatted output for display purposes:
df.style.format("{:,.0f}")
result:
sales | |
---|---|
0 | 1,000 |
1 | 15,000 |
2 | 2,500,000 |
Multiple Columns with Custom Format
To apply this to multiple numeric columns:
col_format = {"sales": "{:,.0f}", "col2": "{:,.0f}"}
df.head().style.format(col_format)
result:
sales | |
---|---|
0 | 1,000 |
1 | 15,000 |
2 | 2,500,000 |
Format Column with Commas - New Column
Use .apply
with Python’s built-in format
function to create a new column or update existing one:
import pandas as pd
df = pd.DataFrame({
'sales': [1000, 15000, 2500000]
})
df['sales_nice'] = df['sales'].apply(lambda x: f"{x:,}")
Output:
sales | sales_nice | |
---|---|---|
0 | 1000 | 1,000 |
1 | 15000 | 15,000 |
2 | 2500000 | 2,500,000 |