在呈現數據的同時,以所需的格式顯示數據也是一個重要而關鍵的部分。有時,值太大了,我們只想顯示其中所需的部分,或者我們可以說以某種所需的格式。
讓我們看看在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}'.formatprint('\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}'.formatprint('\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}'.formatprint('\nResult :\n', dataframe)