Displaying unitful dataframes

What is the recommended procedure for displaying Unitful Dataframes?
Example:

using DataFrames, Unitful
d = (0:10:1000)u"m"
v = 1500u"m/s" .+ 1.5u"1/s"*d
t = [0u"s"; cumsum(diff(d) ./ v[1:end-1])]
df = DataFrame(depth=d, velocity=v, time=t)

df displays like this:

 Row │ depth      velocity       time
     │ Quantity…  Quantity…      Quantity…    
─────┼────────────────────────────────────────
   1 │       0 m  1500.0 m s^-1         0.0 s
   2 │      10 m  1515.0 m s^-1  0.00666667 s
   3 │      20 m  1530.0 m s^-1   0.0132673 s
  ⋮  │     ⋮            ⋮             ⋮
  99 │     980 m  2970.0 m s^-1    0.457052 s
 100 │     990 m  2985.0 m s^-1    0.460419 s
 101 │    1000 m  3000.0 m s^-1    0.463769 s

Ideally, the units should appear clearly and only below the column names. Thank you.

I don’t know if someone has made this, but it definitely sounds like a good PR for PrettyTables, or a UnitfulDataFrames package, depending on the former’s policy on dependencies (Add it to the list of packages that would be obsoleted with https://github.com/JuliaLang/Pkg.jl/issues/1285)

1 Like

Thank you for the feedback.

It seems that PrettyTables.jl can already be used as is but one needs to labor a bit and precondition the inputs as follows:

using DataFrames, Unitful, PrettyTables

d = (0:10:1000)u"m"
v = 1500u"m/s" .+ 1.5u"1/s"*d
t = [0u"s"; cumsum(diff(d) ./ v[1:end-1])]
df = DataFrame(depth=d, velocity=v, time=t)
sunits = [unit(d[1]), unit(v[1]), unit(t[1])]
header = permutedims([names(df) sunits])
pretty_table(ustrip.(df), header; formatters = ft_printf("%.4f",[3]))

Result:

┌───────┬──────────┬────────┐
│ depth │ velocity │   time │
│     m │   m s^-1 │      s │
├───────┼──────────┼────────┤
│     0 │   1500.0 │ 0.0000 │
│    10 │   1515.0 │ 0.0067 │
│    20 │   1530.0 │ 0.0133 │
│    30 │   1545.0 │ 0.0198 │
│    40 │   1560.0 │ 0.0263 │
│    50 │   1575.0 │ 0.0327 │
│    60 │   1590.0 │ 0.0390 │
│   ⋮   │    ⋮     │   ⋮    │
└───────┴──────────┴────────┘
              94 rows omitted

NB: use keyword argument crop=:none to show all

Copying @Ronis_BR to ask if this could be automated.

1 Like

Single-argument ustrip is a bit dangerous. If this is automated, it should probably use ustrip.(units, quantities)

1 Like