Formatting thousand separator for integers in a pandas dataframe

前端 未结 3 2330
自闭症患者
自闭症患者 2021-02-15 16:16

I\'m trying to use \'{:,}\'.format(number) like the example below to format a number in a pandas dataframe:

# This works for floats and integers
pri         


        
3条回答
  •  逝去的感伤
    2021-02-15 17:03

    The formatters parameter in to_html will take a dictionary of column names mapped to a formatting function. Below has an example of a function to build a dict that maps the same function to both floats and ints.

    In [250]: num_format = lambda x: '{:,}'.format(x)
    
    In [246]: def build_formatters(df, format):
         ...:     return {column:format 
         ...:               for (column, dtype) in df.dtypes.iteritems()
         ...:               if dtype in [np.dtype('int64'), np.dtype('float64')]}
         ...: 
    
    In [247]: formatters = build_formatters(df_int, num_format)
    
    
    In [249]: print df_int.to_html(formatters=formatters)
    
    A
    0 20,000
    1 10,000

提交回复
热议问题