1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
open Ast
open Arrow_table

(*
--# Fill missing values
--#
--# Fills missing values in selected columns using the next or previous entry.
--#
--# @name fill
--# @param df :: DataFrame The DataFrame.
--# @param ... :: Symbol Columns to fill (use $col syntax).
--# @param .direction :: String (Optional) Direction in which to fill missing values. 
--#   Options: "down" (default), "up", "downup", "updown".
--# @return :: DataFrame The filled DataFrame.
--# @example
--#   fill(df, $category, .direction = "down")
--# @family colcraft
--# @export
*)
let register env =
  Env.add "fill"
    (make_builtin_named ~name:"fill" ~variadic:true 1 (fun named_args _env ->
      let df_arg = match named_args with
        | (_, VDataFrame df) :: _ -> Some df
        | _ -> None
      in
      
      let get_named k = List.find_map (fun (nk, v) -> if nk = Some k then Some v else None) named_args in
      let positional = List.filter_map (fun (k, v) -> if k = None then Some v else None) named_args in
      
      let direction = match get_named ".direction" with
        | Some (VString s) -> s
        | _ -> "down"
      in
      
      let cols_variants = match positional with _::tail -> tail | [] -> [] in
      let cols_to_fill = List.filter_map Utils.extract_column_name cols_variants in

      match df_arg with
      | None -> Error.type_error "Function `fill` expects a DataFrame as first argument."
      | Some df ->
          let valid_directions = ["down"; "up"; "downup"; "updown"] in
          if not (List.mem direction valid_directions) then
            Error.type_error (Printf.sprintf "Function `fill` received invalid `.direction` value: \"%s\". Supported values are: down, up, downup, updown." direction)
          else if cols_to_fill = [] then
            Error.type_error "Function `fill` expects at least one column to fill using $col syntax."
          else
          
          let orig_nrows = Arrow_table.num_rows df.arrow_table in
          let all_cols = Arrow_table.column_names df.arrow_table in
          
          let missing_cols = List.filter (fun c -> not (List.mem c all_cols)) cols_to_fill in
          if missing_cols <> [] then 
            Error.make_error KeyError (Printf.sprintf "Function `fill`: column(s) not found: %s" (String.concat ", " missing_cols))
          else
            
            let fill_col col_name data =
              let new_arr = match data with
                | IntColumn a ->
                    let b = Array.copy a in
                    let last = ref None in
                    if direction = "down" || direction = "downup" then
                      for i = 0 to orig_nrows - 1 do
                        match b.(i) with
                        | Some _ as v -> last := v
                        | None -> b.(i) <- !last
                      done;
                    if direction = "up" || direction = "updown" || (direction = "downup" && Array.exists Option.is_none b) then
                      begin
                        last := None;
                        for i = orig_nrows - 1 downto 0 do
                          match b.(i) with
                          | Some _ as v -> last := v
                          | None -> b.(i) <- !last
                        done;
                        if direction = "updown" then (* if still has NAs, fill down *)
                          begin
                             last := None;
                             for i = 0 to orig_nrows - 1 do
                               match b.(i) with
                               | Some _ as v -> last := v
                               | None -> b.(i) <- !last
                             done
                          end
                      end;
                    IntColumn b
                | FloatColumn a ->
                    let b = Array.copy a in
                    let last = ref None in
                    if direction = "down" || direction = "downup" then
                      for i = 0 to orig_nrows - 1 do
                        match b.(i) with
                        | Some _ as v -> last := v
                        | None -> b.(i) <- !last
                      done;
                    if direction = "up" || direction = "updown" || (direction = "downup" && Array.exists Option.is_none b) then
                      begin
                        last := None;
                        for i = orig_nrows - 1 downto 0 do
                          match b.(i) with
                          | Some _ as v -> last := v
                          | None -> b.(i) <- !last
                        done;
                        if direction = "updown" then
                           begin
                             last := None;
                             for i = 0 to orig_nrows - 1 do
                               match b.(i) with
                               | Some _ as v -> last := v
                               | None -> b.(i) <- !last
                             done
                           end
                      end;
                    FloatColumn b
                | StringColumn a ->
                    let is_missing = function
                      | None -> true
                      | Some "NA" | Some "na" | Some "N/A" -> true
                      | _ -> false
                    in
                    let b = Array.copy a in
                    let last = ref None in
                    if direction = "down" || direction = "downup" then
                      for i = 0 to orig_nrows - 1 do
                        if not (is_missing b.(i)) then last := b.(i)
                        else b.(i) <- !last
                      done;
                    if direction = "up" || direction = "updown" || (direction = "downup" && Array.exists is_missing b) then
                      begin
                        last := None;
                        for i = orig_nrows - 1 downto 0 do
                          if not (is_missing b.(i)) then last := b.(i)
                          else b.(i) <- !last
                        done;
                        if direction = "updown" then
                           begin
                             last := None;
                             for i = 0 to orig_nrows - 1 do
                               if not (is_missing b.(i)) then last := b.(i)
                               else b.(i) <- !last
                             done
                           end
                      end;
                    StringColumn b
                | BoolColumn a ->
                    let b = Array.copy a in
                    let last = ref None in
                    if direction = "down" || direction = "downup" then
                      for i = 0 to orig_nrows - 1 do
                        match b.(i) with
                        | Some _ as v -> last := v
                        | None -> b.(i) <- !last
                      done;
                    if direction = "up" || direction = "updown" || (direction = "downup" && Array.exists Option.is_none b) then
                      begin
                        last := None;
                        for i = orig_nrows - 1 downto 0 do
                          match b.(i) with
                          | Some _ as v -> last := v
                          | None -> b.(i) <- !last
                        done;
                        if direction = "updown" then
                           begin
                             last := None;
                             for i = 0 to orig_nrows - 1 do
                               match b.(i) with
                               | Some _ as v -> last := v
                               | None -> b.(i) <- !last
                             done
                            end
                       end;
                    BoolColumn b
                | DateColumn a ->
                    let b = Array.copy a in
                    let last = ref None in
                    if direction = "down" || direction = "downup" then
                      for i = 0 to orig_nrows - 1 do
                        match b.(i) with
                        | Some _ as v -> last := v
                        | None -> b.(i) <- !last
                      done;
                    if direction = "up" || direction = "updown" || (direction = "downup" && Array.exists Option.is_none b) then
                      begin
                        last := None;
                        for i = orig_nrows - 1 downto 0 do
                          match b.(i) with
                          | Some _ as v -> last := v
                          | None -> b.(i) <- !last
                        done;
                        if direction = "updown" then
                           begin
                             last := None;
                             for i = 0 to orig_nrows - 1 do
                               match b.(i) with
                               | Some _ as v -> last := v
                               | None -> b.(i) <- !last
                             done
                           end
                      end;
                    DateColumn b
                | DatetimeColumn (a, tz) ->
                    let b = Array.copy a in
                    let last = ref None in
                    if direction = "down" || direction = "downup" then
                      for i = 0 to orig_nrows - 1 do
                        match b.(i) with
                        | Some _ as v -> last := v
                        | None -> b.(i) <- !last
                      done;
                    if direction = "up" || direction = "updown" || (direction = "downup" && Array.exists Option.is_none b) then
                      begin
                        last := None;
                        for i = orig_nrows - 1 downto 0 do
                          match b.(i) with
                          | Some _ as v -> last := v
                          | None -> b.(i) <- !last
                        done;
                        if direction = "updown" then
                           begin
                             last := None;
                             for i = 0 to orig_nrows - 1 do
                               match b.(i) with
                               | Some _ as v -> last := v
                               | None -> b.(i) <- !last
                             done
                           end
                      end;
                    DatetimeColumn (b, tz)
                | DictionaryColumn (a, levels, ordered) ->
                    let b = Array.copy a in
                    let last = ref None in
                    if direction = "down" || direction = "downup" then
                      for i = 0 to orig_nrows - 1 do
                        match b.(i) with
                        | Some _ as v -> last := v
                        | None -> b.(i) <- !last
                      done;
                    if direction = "up" || direction = "updown" || (direction = "downup" && Array.exists Option.is_none b) || (direction = "updown" && Array.exists Option.is_none b) then
                      begin
                        last := None;
                        for i = orig_nrows - 1 downto 0 do
                          match b.(i) with
                          | Some _ as v -> last := v
                          | None -> b.(i) <- !last
                        done;
                        if direction = "updown" then
                           begin
                             last := None;
                             for i = 0 to orig_nrows - 1 do
                               match b.(i) with
                               | Some _ as v -> last := v
                               | None -> b.(i) <- !last
                             done
                           end
                      end;
                    DictionaryColumn (b, levels, ordered)
                | NAColumn n -> NAColumn n
                | ListColumn a -> ListColumn a
              in
              (col_name, new_arr)
            in

            let new_columns = List.map (fun col_name ->
              let col_data = match Arrow_table.get_column df.arrow_table col_name with Some d -> d | None -> NAColumn orig_nrows in
              if List.mem col_name cols_to_fill then
                fill_col col_name col_data
              else
                (col_name, col_data)
            ) all_cols in
            
            let new_schema = List.map (fun (n, c) -> (n, Arrow_table.column_type_of c)) new_columns in
            VDataFrame { arrow_table = { schema = new_schema; columns = new_columns; nrows = orig_nrows; native_handle = None } |> Arrow_table.materialize; group_keys = df.group_keys }
    ))
    env