📜  在 Pandas 中格式化 Dataframe 的浮点列

📅  最后修改于: 2022-05-13 01:55:07.929000             🧑  作者: Mango

在 Pandas 中格式化 Dataframe 的浮点列

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

让我们看看在 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 :\n", dataframe)
  
# round to two decimal places in python pandas
pd.options.display.float_format = '{:.2f}'.format
  
print('\nResult :\n', 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 :\n", dataframe)
  
# Format with commas and round off to two decimal places in pandas
pd.options.display.float_format = '{:, .2f}'.format
  
print('\nResult :\n', 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 :\n", dataframe)
  
# Format with dollars, commas and round off
# to two decimal places in pandas
pd.options.display.float_format = '${:, .2f}'.format
  
print('\nResult :\n', dataframe)

输出: