Pandas格式化DataFrame的浮点数列的实现

原创
ithorizon 9个月前 (07-01) 阅读数 155 #Python
目录
  • 例1:将列值四舍五入到两位小数
  • 例2:用逗号格式化整数列,并四舍五入到两位小数
  • 例3:格式划列与逗号和$符号,并四舍五入到两位小数

在呈现数据的同时,以所需的格式显示数据也是一个重要而关键的部分。有时,值太大了,我们只想显示其中所需的部分,或者我们可以说以某种所需的格式。

让我们看看在Pandas中格式化DataFrame的数值列的不同方法。

例1:将列值四舍五入到两位小数

# 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 :", dataframe) 

# round to two decimal places in python pandas 
pd.options.display.float_format = '{:.2f}'.format

print('Result :', dataframe) 

在这里插入图片描述

例2:用逗号格式化整数列,并四舍五入到两位小数

# 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 :", dataframe) 

# Format with commas and round off to two decimal places in pandas 
pd.options.display.float_format = '{:, .2f}'.format

print('Result :', dataframe) 

在这里插入图片描述

例3:格式划列与逗号和$符号,并四舍五入到两位小数

# 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 :", dataframe) 

# Format with dollars, commas and round off 
# to two decimal places in pandas 
pd.options.display.float_format = '${:, .2f}'.format

print('Result :', dataframe) 

在这里插入图片描述

到此这篇涉及Pandas格式化DataFrame的浮点数列的实现的文章就介绍到这了,更多相关Pandas DataFrame浮点数列内容请搜索IT视界以前的文章或继续浏览下面的相关文章期望大家以后多多赞成IT视界! 


本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: Python


热门