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