Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number with commas to separate thousands in Python

I have a large dataframe, which has a column called Lead Rev. This column is a field of numbers such as (100000 or 5000 etc.) I want to know how to format these numbers to show commas as thousand separators. The dataset has over 200,000 rows.

Is it something like: '{:,}'.format('Lead Rev')

which gives this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-182-5fe9c827d80b> in <module>()
----> 1 '{:,}'.format('Lead Rev')

ValueError: Cannot specify ',' or '_' with 's'.
like image 708
Sandy Tumma Avatar asked Mar 29 '17 19:03

Sandy Tumma


People also ask

Which is a thousand separator in Python?

Reference. Per Format Specification Mini-Language, The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

How do you make a comma separated list in Python?

How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].


3 Answers

To make all your floats show comma separators by default in pandas versions 0.23 through 0.25 set the following:

pd.options.display.float_format = '{:,}'.format

https://pandas.pydata.org/pandas-docs/version/0.23.4/options.html

In pandas version 1.0 this leads to some strange formatting in some cases.

like image 132
jeffhale Avatar answered Oct 13 '22 18:10

jeffhale


You can use apply() to get the desired result. This works with floating too

import pandas as pd

series1 = pd.Series({'Value': 353254})
series2 = pd.Series({'Value': 54464.43})
series3 = pd.Series({'Value': 6381763761})

df = pd.DataFrame([series1, series2, series3])
print(df.head())

         Value
0  3.532540e+05
1  5.446443e+04
2  6.381764e+09

df['Value'] = df.apply(lambda x: "{:,}".format(x['Value']), axis=1)
print(df.head())

             Value
0        353,254.0
1        54,464.43
2  6,381,763,761.0
like image 38
flivan Avatar answered Oct 13 '22 17:10

flivan


df.head().style.format("{:,.0f}") (for all columns)

df.head().style.format({"col1": "{:,.0f}", "col2": "{:,.0f}"}) (per column)

https://pbpython.com/styling-pandas.html

like image 39
Ran Feldesh Avatar answered Oct 13 '22 18:10

Ran Feldesh