Is there a better way to format each individual columns in a dataframe?

Philip_Stuckey
Fri, 15 Mar 2024 18:41:45 +0000
General Usage

I wrote a function to format individual columns of a dataframe and I’m wondering if that’s a good idea or not.

Is there a better way to format the columns of a dataframe before printing to markdown? I found the formatters in PrettyTables difficult to use so I wrote the function

using DataStructures: DefaultDict
using Format
using DataFrames
function format_columns(table; formats...)
    formats = DefaultDict("{}", formats...)
    return DataFrame(
        [k=>format.(formats[Symbol(k)], table[!,k]) for k in names(table)]
    )
end

So I could do this:

format_columns(table,
foo="{:0.1f}",
bar="{:0.2f}",
baz="{:0.2f} dB",
qux="{:0.1%}"
)

and get

5×4 DataFrame
 Row │ foo     bar     baz       qux
     │ String  String  String    String
─────┼──────────────────────────────────
   1 │ 1.0     0.00    0.00 dB   100.0%
   2 │ 1.1     0.05    -0.01 dB  99.8%
   3 │ 1.2     0.09    -0.04 dB  99.2%
   4 │ 1.3     0.13    -0.07 dB  98.3%
   5 │ 1.4     0.17    -0.12 dB  97.2%

Is there an easier way to do this?
Would this be useful to anyone as a package?
Given that I can’t find any other way to do this, I feel like either this isn’t a thing people need to do or my approach is subtly wrong.

7 posts - 4 participants