|
| 1 | +# ------------------------------------------------------------------ |
| 2 | +# Licensed under the MIT License. See LICENSE in the project root. |
| 3 | +# ------------------------------------------------------------------ |
| 4 | + |
| 5 | +""" |
| 6 | + DropConstant() |
| 7 | +
|
| 8 | +Drops the constant columns using the `allequal` function. |
| 9 | +""" |
| 10 | +struct DropConstant <: StatelessFeatureTransform end |
| 11 | + |
| 12 | +isrevertible(::Type{DropConstant}) = true |
| 13 | + |
| 14 | +function applyfeat(::DropConstant, feat, prep) |
| 15 | + cols = Tables.columns(feat) |
| 16 | + names = Tables.columnnames(cols) |> collect |
| 17 | + |
| 18 | + # constant columns |
| 19 | + cnames = filter(names) do name |
| 20 | + x = Tables.getcolumn(cols, name) |
| 21 | + allequal(x) |
| 22 | + end |
| 23 | + cinds = indexin(cnames, names) |
| 24 | + cvalues = [first(Tables.getcolumn(cols, nm)) for nm in cnames] |
| 25 | + |
| 26 | + # selected columns |
| 27 | + snames = setdiff(names, cnames) |
| 28 | + columns = [Tables.getcolumn(cols, nm) for nm in snames] |
| 29 | + |
| 30 | + 𝒯 = (; zip(snames, columns)...) |
| 31 | + newfeat = 𝒯 |> Tables.materializer(feat) |
| 32 | + newfeat, (cinds, cnames, cvalues) |
| 33 | +end |
| 34 | + |
| 35 | +function revertfeat(::DropConstant, newfeat, fcache) |
| 36 | + cols = Tables.columns(newfeat) |
| 37 | + names = Tables.columnnames(cols) |> collect |
| 38 | + columns = Any[Tables.getcolumn(cols, name) for name in names] |
| 39 | + |
| 40 | + cinds, cnames, cvalues = fcache |
| 41 | + |
| 42 | + nrows = _nrows(newfeat) |
| 43 | + for (i, cind) in enumerate(cinds) |
| 44 | + insert!(names, cind, cnames[i]) |
| 45 | + insert!(columns, cind, fill(cvalues[i], nrows)) |
| 46 | + end |
| 47 | + |
| 48 | + 𝒯 = (; zip(names, columns)...) |
| 49 | + 𝒯 |> Tables.materializer(newfeat) |
| 50 | +end |
0 commit comments