The Wayback Machine - https://web.archive.org/web/20241006191943/https://www.geeksforgeeks.org/formatting-integer-column-of-dataframe-in-pandas/
Open In App

Formatting float column of Dataframe in Pandas

Last Updated : 10 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

While presenting the data, showing the data in the required format is also a crucial part. Sometimes, the value is so big that we want to show only the desired part of this or we can say in some desired format. Let’s see different methods of formatting integer columns and the data frame it in Pandas.

Formatting float column of Dataframe in Pandas

Here, are various ways to Number formatting in Pandas in Python. So we are explaining some generally used ways and methods for Number formatting in Pandas in the following.

Round off the Column Values to Two Decimal Places

In this example, the below code uses the pandas’ library to create a Pandas DataFrame named ‘data frame’ from a dictionary containing monthly expenses. It then prints the original data frame. After setting the pandas option to display float values with two decimal places.

Python3




# import pandas lib as pd
import pandas as pd
 
# create the data dictionary
data = {'Month': ['January', 'February', 'March', 'April'],
        'Expense': [21525220.653, 31125840.875, 23135428.768, 56245263.942]}
 
# create the dataframe
dataframe = pd.DataFrame(data, columns=['Month', 'Expense'])
 
print("Given Dataframe :\n", dataframe)
 
# round to two decimal places in python pandas
pd.options.display.float_format = '{:.2f}'.format
 
print('\nResult :\n', dataframe)


Output:

Given Dataframe :
Month Expense
0 January 2.152522e+07
1 February 3.112584e+07
2 March 2.313543e+07
3 April 5.624526e+07
Result :
Month Expense
0 January 21525220.65
1 February 31125840.88
2 March 23135428.77
3 April 56245263.94

Pandas DataFrame Formatting with Commas and Decimal Precision

In this example below code uses pandas to create a DataFrame, ‘products_dataframe,’ with product names and their respective prices. It prints the initial DataFrame and then formats the ‘Price’ column with commas and rounds the values to two decimal places.

Python3




import pandas as pd
 
# Create a data dictionary
data = {'Product': ['Laptop', 'Phone', 'Tablet', 'Desktop'],
        'Price': [1200.50, 799.99, 349.75, 1500.25]}
 
# Create a DataFrame
products_dataframe = pd.DataFrame(data, columns=['Product', 'Price'])
 
print("Given Dataframe :\n", products_dataframe)
 
# Format with commas and round off to two decimal places in pandas
pd.options.display.float_format = '{:,.2f}'.format
 
# Create a new DataFrame with formatted values
formatted_products = products_dataframe.copy()
formatted_products['Price'] = formatted_products['Price'].apply(lambda x: '{:,.2f}'.format(x))
 
# Display the formatted DataFrame
print('\nResult :\n', formatted_products)


Output:

Given Dataframe :
Product Price
0 Laptop 1,200.50
1 Phone 799.99
2 Tablet 349.75
3 Desktop 1,500.25
Result :
Product Price
0 Laptop 1,200.50
1 Phone 799.99
2 Tablet 349.75
3 Desktop 1,500.25

Formatting and Scaling Population Data in Pandas DataFrame

In this example code utilizes the pandas library to create a DataFrame named ‘city_dataframe’ with city names and their respective populations. Initially displaying the DataFrame, it later formats the population column with commas and scales the values to millions.

Python3




import pandas as pd
 
# Create a data dictionary
data = {'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'],
        'Population': [8336817, 3980400, 2716000, 2328000]}
 
# Create a DataFrame
city_dataframe = pd.DataFrame(data, columns=['City', 'Population'])
 
# Display the initial DataFrame
print("Given DataFrame:\n", city_dataframe)
 
# Format with commas and display population in millions
pd.options.display.float_format = '{:,.2f}'.format
city_dataframe['Population'] = city_dataframe['Population'] / 1000000  # Convert population to millions
 
print('\nResult:\n', city_dataframe)


Output:

Given DataFrame:
City Population
0 New York 8336817
1 Los Angeles 3980400
2 Chicago 2716000
3 Houston 2328000
Result:
City Population
0 New York 8.34
1 Los Angeles 3.98
2 Chicago 2.72
3 Houston 2.33


Previous Article
Next Article

Similar Reads

Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
Get column index from column name of a given Pandas DataFrame
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together. Syntax: DataFrame.columns Return: column names index Syntax: Index.get_loc(key, method=None, tolerance=None) Return: loc : int if unique index, slice if monotonic index, els
2 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
How to Convert Float to Datetime in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=
3 min read
How to Convert String to Float in Pandas DataFrame
Converting Strings to Float in Pandas DataFrame is a very crucial step for data analysis. Converting string to float values can help you perform various arithmetic operations and plot graphs. In this article, we'll look at different ways to convert a string to a float in DataFrame. Creating Sample Dataframe Now, let's create a DataFrame with 'Year'
4 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Change column names and row indexes in Pandas DataFrame
Given a Pandas DataFrame, let's see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns.Each row is a measurement of some instance while column is a vector which
4 min read
Apply uppercase to a column in Pandas dataframe
Analyzing a real world data is some what difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to uppercase each letter in any specific column in given dataframe. Let's see how
2 min read
How to lowercase strings in a column in Pandas dataframe
Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to lowercase each letter in any specific column in given dataframe. Let's see how to
2 min read
Get n-smallest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-smallest values from a particular column in Pandas DataFrame. Observe this dataset first. We'll use 'Age', 'Weight' and 'Salary' columns of this data in order to get n-smallest value
1 min read
Get n-largest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-largest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values
1 min read
Split a text column into two columns in Pandas DataFrame
Let's see how to split a text column into two columns in Pandas DataFrame. Method #1 : Using Series.str.split() functions. Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function. # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Name': ['J
3 min read
Create a column using for loop in Pandas Dataframe
Adding a new column in an already created dataframe is quite easy. Adding a new column is actually required to process the data of dataframe created earlier. For that purpose, we can process the existing data and make a separate column to store the data. The simplest way to add a new column along with data is by creating a new column and assigning
3 min read
Getting Unique values from a column in Pandas dataframe
Let's see how can we retrieve the unique values from pandas dataframe. Let's create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. # import pandas as pd import pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csv record = pd.read_csv(gapmi
2 min read
Split a column in Pandas dataframe and get part of it
When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement. We can use Pandas .str accessor, it does fast vectorized string operations for Series and Dataframes and returns a string object. Pandas str accessor has number of useful methods and one of them is str.spli
2 min read
Return the Index label if some condition is satisfied over a column in Pandas Dataframe
Given a Dataframe, return all those index labels for which some condition is satisfied over a specific column. Solution #1: We can use simple indexing operation to select all those values in the column which satisfies the given condition. C/C++ Code # importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({'Date':['10/2
2 min read
Check if a column starts with given string in Pandas DataFrame?
In this program, we are trying to check whether the specified column in the given data frame starts with specified string or not. Let us try to understand this using an example suppose we have a dataset named student_id, date_of_joining, branch. Example: C/C++ Code #importing library pandas as pd import pandas as pd #creating data frame for student
2 min read
How to Convert Dataframe column into an index in Python-Pandas?
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", "Pankaj
2 min read
How to Convert Index to Column in Pandas Dataframe?
Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learning models and Analyzing data. Converting Index to
2 min read
How to Sort a Pandas DataFrame based on column names or row index?
Pandas dataframe.sort_index() method sorts objects by labels along the given axis. Basically, the sorting algorithm is applied to the axis labels rather than the actual data in the Dataframe and based on that the data is rearranged. Creating Pandas Dataframe Create a DataFrame object from the Python list of tuples with columns and indices, say colu
3 min read