Format a number with commas to separate thousands in pandas

Given a pandas dataframe, we have to format a number with commas to separate thousands.
Submitted by Pranit Sharma, on September 14, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Formatting a number with commas to separate thousands

Suppose, we have a large DataFrame with a column named X. This column has a field of large numbers (in thousands or lakhs). We need to format these numbers by putting commas in between the digits for proper data analysis.

For this purpose, we will use pd.options.display method which contains a feature called float_format which will allow us to format these numbers in such a way that they can be separated with commas.

Let us understand with the help of an example,

Python code to format a number with commas to separate thousands in pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
     'X':[3128793,
          25728342423,
          24292742,
          345794,
          3968432,
          42075045]
     }

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Formatting DataFrame
df['X'] = df.apply(lambda x: "{:,}".format(x['X']), axis=1)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output:

Example: Format a number with commas to separate thousands

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.