Skip to content

Cleaning

toolbox_pyspark.cleaning 🔗

Summary

The cleaning module is used to clean, fix, and fetch various aspects on a given DataFrame.

create_empty_dataframe 🔗

create_empty_dataframe(
    spark_session: SparkSession,
) -> psDataFrame
Source code in src/toolbox_pyspark/cleaning.py
104
105
106
@typechecked
def create_empty_dataframe(spark_session: SparkSession) -> psDataFrame:
    return spark_session.createDataFrame([], T.StructType([]))

keep_first_record_by_columns 🔗

keep_first_record_by_columns(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
) -> psDataFrame

Summary

For a given Spark DataFrame, keep the first record given by the column(s) specified in columns.

Details

The necessity for this function arose when we needed to perform a distinct() function for a given DataFrame; however, we still wanted to retain data provided in the other columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame that you want to filter.

required
columns Union[str, str_collection]

The single or multiple columns by which you want to extract the distinct values from.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If any of the columns do not exist within dataframe.columns.

Returns:

Type Description
DataFrame

The updated dataframe, retaining only the first unique set of records from the columns specified in columns.

Examples

Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import keep_first_record_by_columns
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...             "c": [1, 1, 2, 2],
...             "d": [1, 2, 2, 2],
...             "e": [1, 1, 2, 3],
...         }
...     )
... )
>>>
>>> # Check
>>> df.show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 2 | b | 1 | 2 | 1 |
| 3 | c | 2 | 2 | 2 |
| 4 | d | 2 | 2 | 3 |
+---+---+---+---+---+

Example 1: Distinct by the `c` column
1
>>> keep_first_record_by_columns(df, "c").show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 3 | c | 2 | 2 | 2 |
+---+---+---+---+---+

Conclusion: Successfully kept first records by the c column.

Example 2: Distinct by the `d` column
1
>>> keep_first_record_by_columns(df, "d").show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 2 | b | 1 | 2 | 1 |
+---+---+---+---+---+

Conclusion: Successfully kept first records by the d column.

Example 3: Distinct by the `e` column
1
>>> keep_first_record_by_columns(df, "e").show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 3 | c | 2 | 2 | 2 |
| 4 | d | 2 | 2 | 3 |
+---+---+---+---+---+

Conclusion: Successfully kept first records by the e column.

Example 4: Distinct by the `c` & `d` columns
1
>>> keep_first_record_by_columns(df, ["c", "d"]).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 2 | b | 1 | 2 | 1 |
| 3 | c | 2 | 2 | 2 |
+---+---+---+---+---+

Conclusion: Successfully kept first records by the c & d columns.

Example 5: Distinct by the `c` & `e` columns
1
>>> keep_first_record_by_columns(df, ["c", "e"]).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 3 | c | 2 | 2 | 2 |
| 4 | d | 2 | 2 | 3 |
+---+---+---+---+---+

Conclusion: Successfully kept first records by the c & e columns.

Example 6: Distinct by the `d` & `e` columns
1
>>> keep_first_record_by_columns(df, ["d", "e"]).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 2 | b | 1 | 2 | 1 |
| 3 | c | 2 | 2 | 2 |
| 4 | d | 2 | 2 | 3 |
+---+---+---+---+---+

Conclusion: Successfully kept first records by the d & e columns.

Example 7: Distinct by the `c`, `d` & `e` columns
1
>>> keep_first_record_by_columns(df, ["c", "d", "e"]).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 1 | 1 |
| 2 | b | 1 | 2 | 1 |
| 3 | c | 2 | 2 | 2 |
| 4 | d | 2 | 2 | 3 |
+---+---+---+---+---+

Conclusion: Successfully kept first records by the c, d & e columns.

Conclusion: Failure.

Example 8: Column missing
1
>>> keep_first_record_by_columns(df, "f")
Terminal
ColumnDoesNotExistError: Column 'f' does not exist in the DataFrame.
Try one of: ["a", "b", "c", "d", "e"]

Conclusion: Column missing.

Notes

The way this process will retain only the first record in the given columns is by:

  1. Add a new column called RowNum
    1. This RowNum column uses the SparkSQL function ROW_NUMBER()
    2. The window-function OVER clause will then:
      1. PARTITION BY the columns,
      2. ORDER BY the columns.
  2. Filter so that RowNum=1.
  3. Drop the RowNum column.
See Also
Source code in src/toolbox_pyspark/cleaning.py
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
@typechecked
def keep_first_record_by_columns(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
) -> psDataFrame:
    """
    !!! note "Summary"
        For a given Spark `#!py DataFrame`, keep the first record given by the column(s) specified in `#!py columns`.

    ???+ abstract "Details"
        The necessity for this function arose when we needed to perform a `#!py distinct()` function for a given `#!py DataFrame`; however, we still wanted to retain data provided in the other columns.

    Params:
        dataframe (psDataFrame):
            The DataFrame that you want to filter.
        columns (Union[str, str_collection]):
            The single or multiple columns by which you want to extract the distinct values from.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If any of the `#!py columns` do not exist within `#!py dataframe.columns`.

    Returns:
        (psDataFrame):
            The updated dataframe, retaining only the first unique set of records from the columns specified in `#!py columns`.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import keep_first_record_by_columns
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": [1, 1, 2, 2],
        ...             "d": [1, 2, 2, 2],
        ...             "e": [1, 1, 2, 3],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Check
        >>> df.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 2 | b | 1 | 2 | 1 |
        | 3 | c | 2 | 2 | 2 |
        | 4 | d | 2 | 2 | 3 |
        +---+---+---+---+---+
        ```
        </div>

        ```{.py .python linenums="1" title="Example 1: Distinct by the `c` column"}
        >>> keep_first_record_by_columns(df, "c").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 3 | c | 2 | 2 | 2 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully kept first records by the `c` column."
        </div>

        ```{.py .python linenums="1" title="Example 2: Distinct by the `d` column"}
        >>> keep_first_record_by_columns(df, "d").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 2 | b | 1 | 2 | 1 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully kept first records by the `d` column."
        </div>

        ```{.py .python linenums="1" title="Example 3: Distinct by the `e` column"}
        >>> keep_first_record_by_columns(df, "e").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 3 | c | 2 | 2 | 2 |
        | 4 | d | 2 | 2 | 3 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully kept first records by the `e` column."
        </div>

        ```{.py .python linenums="1" title="Example 4: Distinct by the `c` & `d` columns"}
        >>> keep_first_record_by_columns(df, ["c", "d"]).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 2 | b | 1 | 2 | 1 |
        | 3 | c | 2 | 2 | 2 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully kept first records by the `c` & `d` columns."
        </div>

        ```{.py .python linenums="1" title="Example 5: Distinct by the `c` & `e` columns"}
        >>> keep_first_record_by_columns(df, ["c", "e"]).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 3 | c | 2 | 2 | 2 |
        | 4 | d | 2 | 2 | 3 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully kept first records by the `c` & `e` columns."
        </div>

        ```{.py .python linenums="1" title="Example 6: Distinct by the `d` & `e` columns"}
        >>> keep_first_record_by_columns(df, ["d", "e"]).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 2 | b | 1 | 2 | 1 |
        | 3 | c | 2 | 2 | 2 |
        | 4 | d | 2 | 2 | 3 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully kept first records by the `d` & `e` columns."
        </div>

        ```{.py .python linenums="1" title="Example 7: Distinct by the `c`, `d` & `e` columns"}
        >>> keep_first_record_by_columns(df, ["c", "d", "e"]).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 1 | 1 |
        | 2 | b | 1 | 2 | 1 |
        | 3 | c | 2 | 2 | 2 |
        | 4 | d | 2 | 2 | 3 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully kept first records by the `c`, `d` & `e` columns."
        !!! failure "Conclusion: Failure."
        </div>

        ```{.py .python linenums="1" title="Example 8: Column missing"}
        >>> keep_first_record_by_columns(df, "f")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Column 'f' does not exist in the DataFrame.
        Try one of: ["a", "b", "c", "d", "e"]
        ```
        !!! failure "Conclusion: Column missing."
        </div>

    ??? info "Notes"
        The way this process will retain only the first record in the given `#!py columns` is by:

        1. Add a new column called `RowNum`
            1. This `RowNum` column uses the SparkSQL function `#!sql ROW_NUMBER()`
            1. The window-function `#!sql OVER` clause will then:
                1. `#!sql PARTITION BY` the `#!py columns`,
                1. `#!sql ORDER BY` the `#!py columns`.
        1. Filter so that `#!sql RowNum=1`.
        1. Drop the `#!py RowNum` column.

    ??? tip "See Also"
        - [`toolbox_pyspark.checks.assert_columns_exists()`][toolbox_pyspark.checks.assert_columns_exists]
    """
    columns = [columns] if is_type(columns, str) else columns
    assert_columns_exists(dataframe, columns)
    return (
        dataframe.withColumn(
            colName="RowNum",
            col=F.expr(
                f"""
                ROW_NUMBER()
                OVER
                (
                    PARTITION BY {','.join(columns)}
                    ORDER BY {','.join(columns)}
                )
                """
            ),
        )
        .where("RowNum=1")
        .drop("RowNum")
    )

convert_dataframe 🔗

convert_dataframe(
    dataframe: psDataFrame,
    return_type: Union[
        LITERAL_PYSPARK_DATAFRAME_NAMES,
        LITERAL_PANDAS_DATAFRAME_NAMES,
        LITERAL_NUMPY_ARRAY_NAMES,
        LITERAL_LIST_OBJECT_NAMES,
        str,
    ] = "pd",
) -> Optional[
    Union[psDataFrame, pdDataFrame, npArray, list]
]

Summary

Convert a PySpark DataFrame to the desired return type.

Details

This function converts a PySpark DataFrame to one of the supported return types, including:

PySpark DataFrame:

  • "spark.DataFrame"
  • "pyspark.DataFrame"
  • "pyspark"
  • "spark"
  • "ps.DataFrame"
  • "ps.df"
  • "psdf"
  • "psDataFrame"
  • "psDF"
  • "ps"

Pandas DataFrame:

  • "pandas.DataFrame"
  • "pandas"
  • "pd.DataFrame"
  • "pd.df"
  • "pddf"
  • "pdDataFrame"
  • "pdDF"
  • "pd"

NumPy array:

  • "numpy.array"
  • "np.array"
  • "np"
  • "numpy"
  • "nparr"
  • "npa"
  • "np.arr"
  • "np.a"

Python list:

  • "list"
  • "lst"
  • "l"
  • "flat_list"
  • "flatten_list"

Parameters:

Name Type Description Default
dataframe DataFrame

The PySpark DataFrame to be converted.

required
return_type Union[LITERAL_LIST_OBJECT_NAMES, LITERAL_PANDAS_DATAFRAME_NAMES, LITERAL_PYSPARK_DATAFRAME_NAMES, LITERAL_NUMPY_ARRAY_NAMES, str]

The desired return type.
Options:

  • "ps": Return the PySpark DataFrame.
  • "pd": Return a Pandas DataFrame.
  • "np": Return a NumPy array.
  • "list": Return a Python list.
  • "list_flat": Return a flat Python list (1D).

Defaults to "pd" (Pandas DataFrame).

'pd'

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ValueError

If any of the values parsed to return_type are not valid options.

Returns:

Type Description
Optional[Union[DataFrame, DataFrame, ndarray, list]]

The converted data in the specified return type.

Examples

Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import convert_dataframe
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pdDataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...         }
...     )
... )
>>>
>>> # Check
>>> df.show()
Terminal
+---+---+
| a | b |
+---+---+
| 0 | a |
| 1 | b |
| 2 | c |
| 3 | d |
+---+---+

Example 1: Convert to PySpark
1
2
3
>>> new_df = convert_dataframe(df, "ps")
>>> print(type(new_df))
>>> new_df.show()
Terminal
<class 'pyspark.sql.dataframe.DataFrame'>
Terminal
+---+---+
| a | b |
+---+---+
| 0 | a |
| 1 | b |
| 2 | c |
| 3 | d |
+---+---+

Conclusion: Successfully converted to PySpark.

Example 2: Convert to Pandas
1
2
3
>>> new_df = convert_dataframe(df, "pd")
>>> print(type(new_df))
>>> print(new_df)
Terminal
<class 'pandas.core.frame.DataFrame'>
Terminal
   a  b
0  0  a
1  1  b
2  2  c
3  3  d

Conclusion: Successfully converted to Pandas.

Example 3: Convert to Numpy
1
2
3
>>> new_df = convert_dataframe(df, "np")
>>> print(type(new_df))
>>> print(new_df)
Terminal
<class 'numpy.ndarray'>
Terminal
[[0 "a"]
 [1 "b"]
 [2 "c"]
 [3 "d"]]

Conclusion: Successfully converted to Numpy.

Example 4: List
1
2
3
>>> new_df = convert_dataframe(df, "list")
>>> print(type(new_df))
>>> print(new_df)
Terminal
<class 'list'>
Terminal
[
    [0, "a"],
    [1, "b"],
    [2, "c"],
    [3, "d"],
]

Conclusion: Successfully converted to List.

Example 5: Convert to single column as list
1
2
3
>>> new_df = convert_dataframe(df.select("b"), "flat_list")
>>> print(type(new_df))
>>> print(new_df)
Terminal
<class 'list'>
Terminal
["a", "b", "c", "d"]

Conclusion: Successfully converted to flat List.

Example 6: Invalid return type
1
>>> convert_dataframe(df, "invalid")
Terminal
ValueError: Unknown return type: 'invalid'.
Must be one of: ['pd', 'ps', 'np', 'list'].
For more info, check the `constants` module.

Conclusion: Invalid return type.

See Also
Source code in src/toolbox_pyspark/cleaning.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
@typechecked
def convert_dataframe(
    dataframe: psDataFrame,
    return_type: Union[
        LITERAL_PYSPARK_DATAFRAME_NAMES,
        LITERAL_PANDAS_DATAFRAME_NAMES,
        LITERAL_NUMPY_ARRAY_NAMES,
        LITERAL_LIST_OBJECT_NAMES,
        str,
    ] = "pd",
) -> Optional[Union[psDataFrame, pdDataFrame, npArray, list]]:
    """
    !!! note "Summary"
        Convert a PySpark DataFrame to the desired return type.

    ???+ abstract "Details"
        This function converts a PySpark DataFrame to one of the supported return types, including:

        PySpark DataFrame:

        <div class="mdx-four-columns" markdown>

        - `#!py "spark.DataFrame"`
        - `#!py "pyspark.DataFrame"`
        - `#!py "pyspark"`
        - `#!py "spark"`
        - `#!py "ps.DataFrame"`
        - `#!py "ps.df"`
        - `#!py "psdf"`
        - `#!py "psDataFrame"`
        - `#!py "psDF"`
        - `#!py "ps"`

        </div>

        Pandas DataFrame:

        <div class="mdx-four-columns" markdown>

        - `#!py "pandas.DataFrame"`
        - `#!py "pandas"`
        - `#!py "pd.DataFrame"`
        - `#!py "pd.df"`
        - `#!py "pddf"`
        - `#!py "pdDataFrame"`
        - `#!py "pdDF"`
        - `#!py "pd"`

        </div>

        NumPy array:

        <div class="mdx-four-columns" markdown>

        - `#!py "numpy.array"`
        - `#!py "np.array"`
        - `#!py "np"`
        - `#!py "numpy"`
        - `#!py "nparr"`
        - `#!py "npa"`
        - `#!py "np.arr"`
        - `#!py "np.a"`

        </div>

        Python list:

        <div class="mdx-four-columns" markdown>

        - `#!py "list"`
        - `#!py "lst"`
        - `#!py "l"`
        - `#!py "flat_list"`
        - `#!py "flatten_list"`

        </div>

    Params:
        dataframe (psDataFrame):
            The PySpark DataFrame to be converted.
        return_type (Union[LITERAL_LIST_OBJECT_NAMES, LITERAL_PANDAS_DATAFRAME_NAMES, LITERAL_PYSPARK_DATAFRAME_NAMES, LITERAL_NUMPY_ARRAY_NAMES, str], optional):
            The desired return type.<br>
            Options:

            - `#!py "ps"`: Return the PySpark DataFrame.
            - `#!py "pd"`: Return a Pandas DataFrame.
            - `#!py "np"`: Return a NumPy array.
            - `#!py "list"`: Return a Python list.
            - `#!py "list_flat"`: Return a flat Python list (1D).

            Defaults to `#!py "pd"` (Pandas DataFrame).

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ValueError:
            If any of the values parsed to `return_type` are not valid options.

    Returns:
        (Optional[Union[psDataFrame, pdDataFrame, npArray, list]]):
            The converted data in the specified return type.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import convert_dataframe
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pdDataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Check
        >>> df.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+
        | a | b |
        +---+---+
        | 0 | a |
        | 1 | b |
        | 2 | c |
        | 3 | d |
        +---+---+
        ```

        ```{.py .python linenums="1" title="Example 1: Convert to PySpark"}
        >>> new_df = convert_dataframe(df, "ps")
        >>> print(type(new_df))
        >>> new_df.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        <class 'pyspark.sql.dataframe.DataFrame'>
        ```
        ```{.txt .text title="Terminal"}
        +---+---+
        | a | b |
        +---+---+
        | 0 | a |
        | 1 | b |
        | 2 | c |
        | 3 | d |
        +---+---+
        ```
        !!! success "Conclusion: Successfully converted to PySpark."
        </div>

        ```{.py .python linenums="1" title="Example 2: Convert to Pandas"}
        >>> new_df = convert_dataframe(df, "pd")
        >>> print(type(new_df))
        >>> print(new_df)
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        <class 'pandas.core.frame.DataFrame'>
        ```
        ```{.txt .text title="Terminal"}
           a  b
        0  0  a
        1  1  b
        2  2  c
        3  3  d
        ```
        !!! success "Conclusion: Successfully converted to Pandas."
        </div>

        ```{.py .python linenums="1" title="Example 3: Convert to Numpy"}
        >>> new_df = convert_dataframe(df, "np")
        >>> print(type(new_df))
        >>> print(new_df)
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        <class 'numpy.ndarray'>
        ```
        ```{.txt .text title="Terminal"}
        [[0 "a"]
         [1 "b"]
         [2 "c"]
         [3 "d"]]
        ```
        !!! success "Conclusion: Successfully converted to Numpy."
        </div>

        ```{.py .python linenums="1" title="Example 4: List"}
        >>> new_df = convert_dataframe(df, "list")
        >>> print(type(new_df))
        >>> print(new_df)
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        <class 'list'>
        ```
        ```{.txt .text title="Terminal"}
        [
            [0, "a"],
            [1, "b"],
            [2, "c"],
            [3, "d"],
        ]
        ```
        !!! success "Conclusion: Successfully converted to List."
        </div>

        ```{.py .python linenums="1" title="Example 5: Convert to single column as list"}
        >>> new_df = convert_dataframe(df.select("b"), "flat_list")
        >>> print(type(new_df))
        >>> print(new_df)
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        <class 'list'>
        ```
        ```{.txt .text title="Terminal"}
        ["a", "b", "c", "d"]
        ```
        !!! success "Conclusion: Successfully converted to flat List."
        </div>

        ```{.py .python linenums="1" title="Example 6: Invalid return type"}
        >>> convert_dataframe(df, "invalid")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ValueError: Unknown return type: 'invalid'.
        Must be one of: ['pd', 'ps', 'np', 'list'].
        For more info, check the `constants` module.
        ```
        !!! failure "Conclusion: Invalid return type."
        </div>

    ??? tip "See Also"
        - [`toolbox_pyspark.constants`][toolbox_pyspark.constants]
    """
    if return_type in VALID_PYSPARK_DATAFRAME_NAMES:
        return dataframe
    elif return_type in VALID_PANDAS_DATAFRAME_NAMES:
        return dataframe.toPandas()
    elif return_type in VALID_NUMPY_ARRAY_NAMES:
        return dataframe.toPandas().values  # type:ignore
    elif return_type in VALID_LIST_OBJECT_NAMES:
        if "flat" in return_type:
            return flatten(dataframe.toPandas().values.tolist())  # type:ignore
        else:
            return dataframe.toPandas().values.tolist()  # type:ignore
    else:
        raise ValueError(
            f"Unknown return type: '{return_type}'.\n"
            f"Must be one of: {['pd', 'ps', 'np', 'list']}.\n"
            f"For more info, check the `constants` module."
        )

update_nullability 🔗

update_nullability(
    dataframe: psDataFrame,
    columns: Optional[Union[str, str_collection]] = None,
    nullable: bool = True,
) -> psDataFrame

Summary

Update the nullability of specified columns in a PySpark DataFrame.

Details

This function updates the nullability of the specified columns in a PySpark DataFrame. If no columns are specified, it updates the nullability of all columns.

Parameters:

Name Type Description Default
dataframe DataFrame

The input PySpark DataFrame.

required
columns Optional[Union[str, str_collection]]

The columns for which to update nullability. If not provided, all columns will be updated.
Defaults to None.

None
nullable bool

Whether to set the columns as nullable or not.
Defaults to True.

True

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If any of the columns do not exist within dataframe.columns.

Returns:

Type Description
DataFrame

The updated DataFrame with the specified columns' nullability updated.

Examples

Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import update_nullability
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...             "c": [1.1, 2.2, 3.3, 4.4],
...         }
...     )
... )
>>>
>>> # Check
>>> df.show()
>>> print(df.schema)
>>> df.printSchema()
Terminal
+---+---+-----+
| a | b |   c |
+---+---+-----+
| 1 | a | 1.1 |
| 2 | b | 2.2 |
| 3 | c | 3.3 |
| 4 | d | 4.4 |
+---+---+-----+
Terminal
StructType(
    [
        StructField("a", LongType(), True),
        StructField("b", StringType(), True),
        StructField("c", DoubleType(), True),
    ]
)
Terminal
root
 |-- a: long (nullable = true)
 |-- b: string (nullable = true)
 |-- c: double (nullable = true)

Example 1: Update nullability of all columns
1
2
>>> new_df = update_nullability(df, nullable=False)
>>> new_df.printSchema()
Terminal
root
 |-- a: long (nullable = false)
 |-- b: string (nullable = false)
 |-- c: double (nullable = false)

Conclusion: Successfully updated nullability of all columns.

Example 2: Update nullability of specific columns
1
2
>>> new_df = update_nullability(df, columns=["a", "c"], nullable=False)
>>> new_df.printSchema()
Terminal
root
 |-- a: long (nullable = false)
 |-- b: string (nullable = true)
 |-- c: double (nullable = false)

Conclusion: Successfully updated nullability of specific columns.

Example 3: Column does not exist
1
>>> update_nullability(df, columns="d", nullable=False)
Terminal
ColumnDoesNotExistError: Column 'd' does not exist in the DataFrame.
Try one of: ["a", "b", "c"]

Conclusion: Column does not exist.

Credit

All credit goes to: https://stackoverflow.com/questions/46072411/can-i-change-the-nullability-of-a-column-in-my-spark-dataframe#answer-51821437.

See Also
Source code in src/toolbox_pyspark/cleaning.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
@typechecked
def update_nullability(
    dataframe: psDataFrame,
    columns: Optional[Union[str, str_collection]] = None,
    nullable: bool = True,
) -> psDataFrame:
    """
    !!! note "Summary"
        Update the nullability of specified columns in a PySpark DataFrame.

    ???+ abstract "Details"
        This function updates the nullability of the specified columns in a PySpark DataFrame. If no columns are specified, it updates the nullability of all columns.

    Params:
        dataframe (psDataFrame):
            The input PySpark DataFrame.
        columns (Optional[Union[str, str_collection]], optional):
            The columns for which to update nullability. If not provided, all columns will be updated.<br>
            Defaults to `#!py None`.
        nullable (bool, optional):
            Whether to set the columns as nullable or not.<br>
            Defaults to `#!py True`.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If any of the `#!py columns` do not exist within `#!py dataframe.columns`.

    Returns:
        (psDataFrame):
            The updated DataFrame with the specified columns' nullability updated.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import update_nullability
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": [1.1, 2.2, 3.3, 4.4],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Check
        >>> df.show()
        >>> print(df.schema)
        >>> df.printSchema()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+-----+
        | a | b |   c |
        +---+---+-----+
        | 1 | a | 1.1 |
        | 2 | b | 2.2 |
        | 3 | c | 3.3 |
        | 4 | d | 4.4 |
        +---+---+-----+
        ```
        ```{.sh .shell title="Terminal"}
        StructType(
            [
                StructField("a", LongType(), True),
                StructField("b", StringType(), True),
                StructField("c", DoubleType(), True),
            ]
        )
        ```
        ```{.txt .text title="Terminal"}
        root
         |-- a: long (nullable = true)
         |-- b: string (nullable = true)
         |-- c: double (nullable = true)
        ```
        </div>

        ```{.py .python linenums="1" title="Example 1: Update nullability of all columns"}
        >>> new_df = update_nullability(df, nullable=False)
        >>> new_df.printSchema()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        root
         |-- a: long (nullable = false)
         |-- b: string (nullable = false)
         |-- c: double (nullable = false)
        ```
        !!! success "Conclusion: Successfully updated nullability of all columns."
        </div>

        ```{.py .python linenums="1" title="Example 2: Update nullability of specific columns"}
        >>> new_df = update_nullability(df, columns=["a", "c"], nullable=False)
        >>> new_df.printSchema()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        root
         |-- a: long (nullable = false)
         |-- b: string (nullable = true)
         |-- c: double (nullable = false)
        ```
        !!! success "Conclusion: Successfully updated nullability of specific columns."
        </div>

        ```{.py .python linenums="1" title="Example 3: Column does not exist"}
        >>> update_nullability(df, columns="d", nullable=False)
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Column 'd' does not exist in the DataFrame.
        Try one of: ["a", "b", "c"]
        ```
        !!! failure "Conclusion: Column does not exist."
        </div>

    ??? success "Credit"
        All credit goes to: https://stackoverflow.com/questions/46072411/can-i-change-the-nullability-of-a-column-in-my-spark-dataframe#answer-51821437.

    ??? tip "See Also"
        - [`toolbox_pyspark.checks.assert_columns_exists()`][toolbox_pyspark.checks.assert_columns_exists]
    """
    columns = get_columns(dataframe, columns)
    assert_columns_exists(dataframe=dataframe, columns=columns)
    schema: T.StructType = dataframe.schema
    for struct_field in schema:
        if struct_field.name in columns:
            struct_field.nullable = nullable
    return dataframe.sparkSession.createDataFrame(data=dataframe.rdd, schema=dataframe.schema)

trim_spaces_from_column 🔗

trim_spaces_from_column(
    dataframe: psDataFrame, column: str
) -> psDataFrame

Summary

For a given list of columns, trim all of the excess white spaces from them.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to update.

required
column str

The column to clean.

required

Raises:

Type Description
TypeError

If any of the inputs parsed to the parameters of this function are not the correct type. Uses the @typeguard.typechecked decorator.

ColumnDoesNotExistError

If the column does not exist within dataframe.columns.

Returns:

Type Description
DataFrame

The updated Data Frame.

Examples

Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import trim_spaces_from_column
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...             "c": ["1   ", "1   ", "1   ", "1   "],
...             "d": ["   2", "   2", "   2", "   2"],
...             "e": ["   3   ", "   3   ", "   3   ", "   3   "],
...         }
...     )
... )
>>>
>>> # Check
```{.py .python linenums="1" title="Check"}
>>> df.show()
Terminal
+---+---+------+------+---------+
| a | b |    c |    d |       e |
+---+---+------+------+---------+
| 1 | a | 1    |    2 |    3    |
| 2 | b | 1    |    2 |    3    |
| 3 | c | 1    |    2 |    3    |
| 4 | d | 1    |    2 |    3    |
+---+---+------+------+---------+

Example 1: Trim column
1
>>> trim_spaces_from_column(df, "c").show()
Terminal
+---+---+---+------+--------+
| a | b | c |    d |      e |
+---+---+---+------+--------+
| 1 | a | 1 |    2 |   2    |
| 2 | b | 1 |    2 |   2    |
| 3 | c | 1 |    2 |   2    |
| 4 | d | 1 |    2 |   2    |
+---+---+---+------+--------+

Conclusion: Successfully trimmed the c column.

Example 2: Invalid column
1
>>> trim_spaces_from_column(df, "f")
Terminal
ColumnDoesNotExistError: Column 'f' does not exist in the DataFrame.
Try one of: ["a", "b", "c", "d", "e"]

Conclusion: Column does not exist.

Notes
Justification
  • The main reason for this function is because when the data was exported from the Legacy WMS's, there's a whole bunch of trailing spaces in the data fields. My theory is because of the data type in the source system. That is, if it's originally stored as 'char' type, then it will maintain the data length. This issues doesn't seem to be affecting the varchar fields. Nonetheless, this function will strip the white spaces from the data; thus reducing the total size of the data stored therein.
  • The reason why it is necessary to write this out as a custom function, instead of using the F.trim() function from the PySpark library directly is due to the deficiencies of the Java trim() function. More specifically, there are 13 different whitespace characters available in our ascii character set. The Java function only cleans about 6 of these. So therefore, we define this function which iterates through all 13 whitespace characters, and formats them in to a regular expression, to then parse it to the F.regexp_replace() function to be replaced with an empty string (""). Therefore, all 13 characters will be replaced, the strings will be cleaned and trimmed ready for further processing.
Regex definition: ^[...]+|[...]+$
  • 1st Alternative: '^[...]+'
    • '^' asserts position at start of a line
    • Match a single character present in the list below '[...]'
      • '+' matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
      • matches a single character in the list ' ' (case sensitive)
        • matches the character ' ' with index 160 (A0 or 240) literally (case sensitive)
        • matches the character ' ' with index 32 (20 or 40) literally (case sensitive)
        • ... (repeat for all whitespace characters)
  • 2nd Alternative: '[...]+$'
    • Match a single character present in the list below '[...]'
      • '+' matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
      • matches a single character in the list ' ' (case sensitive)
        • matches the character ' ' with index 160 (A0 or 240) literally (case sensitive)
        • matches the character ' ' with index 32 (20 or 40) literally (case sensitive)
        • ... (repeat for all whitespace characters)
    • '$' asserts position at the end of a line
See Also
Source code in src/toolbox_pyspark/cleaning.py
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
@typechecked
def trim_spaces_from_column(
    dataframe: psDataFrame,
    column: str,
) -> psDataFrame:
    """
    !!! note "Summary"
        For a given list of columns, trim all of the excess white spaces from them.

    Params:
        dataframe (psDataFrame):
            The DataFrame to update.
        column (str):
            The column to clean.

    Raises:
        TypeError:
            If any of the inputs parsed to the parameters of this function are not the correct type. Uses the [`@typeguard.typechecked`](https://typeguard.readthedocs.io/en/stable/api.html#typeguard.typechecked) decorator.
        ColumnDoesNotExistError:
            If the `#!py column` does not exist within `#!py dataframe.columns`.

    Returns:
        (psDataFrame):
            The updated Data Frame.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import trim_spaces_from_column
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": ["1   ", "1   ", "1   ", "1   "],
        ...             "d": ["   2", "   2", "   2", "   2"],
        ...             "e": ["   3   ", "   3   ", "   3   ", "   3   "],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Check
        ```{.py .python linenums="1" title="Check"}
        >>> df.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+------+------+---------+
        | a | b |    c |    d |       e |
        +---+---+------+------+---------+
        | 1 | a | 1    |    2 |    3    |
        | 2 | b | 1    |    2 |    3    |
        | 3 | c | 1    |    2 |    3    |
        | 4 | d | 1    |    2 |    3    |
        +---+---+------+------+---------+
        ```
        </div>

        ```{.py .python linenums="1" title="Example 1: Trim column"}
        >>> trim_spaces_from_column(df, "c").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+------+--------+
        | a | b | c |    d |      e |
        +---+---+---+------+--------+
        | 1 | a | 1 |    2 |   2    |
        | 2 | b | 1 |    2 |   2    |
        | 3 | c | 1 |    2 |   2    |
        | 4 | d | 1 |    2 |   2    |
        +---+---+---+------+--------+
        ```
        !!! success "Conclusion: Successfully trimmed the `c` column."
        </div>

        ```{.py .python linenums="1" title="Example 2: Invalid column"}
        >>> trim_spaces_from_column(df, "f")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Column 'f' does not exist in the DataFrame.
        Try one of: ["a", "b", "c", "d", "e"]
        ```
        !!! failure "Conclusion: Column does not exist."
        </div>

    ??? info "Notes"

        ???+ info "Justification"
            - The main reason for this function is because when the data was exported from the Legacy WMS's, there's a _whole bunch_ of trailing spaces in the data fields. My theory is because of the data type in the source system. That is, if it's originally stored as 'char' type, then it will maintain the data length. This issues doesn't seem to be affecting the `varchar` fields. Nonetheless, this function will strip the white spaces from the data; thus reducing the total size of the data stored therein.
            - The reason why it is necessary to write this out as a custom function, instead of using the [`F.trim()`][trim] function from the PySpark library directly is due to the deficiencies of the Java [`trim()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim) function. More specifically, there are 13 different whitespace characters available in our ascii character set. The Java function only cleans about 6 of these. So therefore, we define this function which iterates through all 13 whitespace characters, and formats them in to a regular expression, to then parse it to the [`F.regexp_replace()`][regexp_replace] function to be replaced with an empty string (`""`). Therefore, all 13 characters will be replaced, the strings will be cleaned and trimmed ready for further processing.

            [trim]: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.trim.html
            [regexp_replace]: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.regexp_replace.html

        ???+ info "Regex definition: `^[...]+|[...]+$`"
            - 1st Alternative: '^[...]+'
                - '^' asserts position at start of a line
                - Match a single character present in the list below '[...]'
                    - '+' matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
                    - matches a single character in the list '  ' (case sensitive)
                        - matches the character ' ' with index 160 (A0 or 240) literally (case sensitive)
                        - matches the character ' ' with index 32 (20 or 40) literally (case sensitive)
                        - ... (repeat for all whitespace characters)
            - 2nd Alternative: '[...]+$'
                - Match a single character present in the list below '[...]'
                    - '+' matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
                    - matches a single character in the list '  ' (case sensitive)
                        - matches the character ' ' with index 160 (A0 or 240) literally (case sensitive)
                        - matches the character ' ' with index 32 (20 or 40) literally (case sensitive)
                        - ... (repeat for all whitespace characters)
                - '$' asserts position at the end of a line

    ??? tip "See Also"
        - [`trim_spaces_from_columns()`][toolbox_pyspark.cleaning.trim_spaces_from_columns]
        - [`ALL_WHITESPACE_CHARACTERS`][toolbox_pyspark.constants.ALL_WHITESPACE_CHARACTERS]
    """
    assert_column_exists(dataframe=dataframe, column=column, match_case=True)
    space_chars: str_list = [chr(char.ascii) for char in WHITESPACES]
    regexp: str = f"^[{''.join(space_chars)}]+|[{''.join(space_chars)}]+$"
    return dataframe.withColumn(column, F.regexp_replace(column, regexp, ""))

trim_spaces_from_columns 🔗

trim_spaces_from_columns(
    dataframe: psDataFrame,
    columns: Optional[Union[str, str_collection]] = None,
) -> psDataFrame

Summary

For a given list of columns, trim all of the excess white spaces from them.

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to be updated.

required
columns Optional[Union[str, str_collection]]

The list of columns to be updated. Must be valid columns on dataframe. If given as a string, will be executed as a single column (ie. one-element long list). If not given, will apply to all columns in dataframe which have the data-type string. It is also possible to parse the values "all" or "all_string", which will also apply this function to all columns in dataframe which have the data-type string.
Defaults to None.

None

Returns:

Type Description
DataFrame

The updated DataFrame.

Examples

Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import trim_spaces_from_columns
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [1, 2, 3, 4],
...             "b": ["a", "b", "c", "d"],
...             "c": ["1   ", "1   ", "1   ", "1   "],
...             "d": ["   2", "   2", "   2", "   2"],
...             "e": ["   3   ", "   3   ", "   3   ", "   3   "],
...         }
...     )
... )
>>>
>>> # Check
```{.py .python linenums="1" title="Check"}
>>> df.show()
Terminal
+---+---+------+------+---------+
| a | b |    c |    d |       e |
+---+---+------+------+---------+
| 1 | a | 1    |    2 |    3    |
| 2 | b | 1    |    2 |    3    |
| 3 | c | 1    |    2 |    3    |
| 4 | d | 1    |    2 |    3    |
+---+---+------+------+---------+

Example 1: One column as list
1
>>> trim_spaces_from_columns(df, ["c"]).show()
Terminal
+---+---+---+------+---------+
| a | b | c |    d |       e |
+---+---+---+------+---------+
| 1 | a | 1 |    2 |    3    |
| 2 | b | 1 |    2 |    3    |
| 3 | c | 1 |    2 |    3    |
| 4 | d | 1 |    2 |    3    |
+---+---+---+------+---------+

Conclusion: Successfully trimmed the c column.

Example 2: Single column as string
1
>>> trim_spaces_from_columns(df, "d").show()
Terminal
+---+---+------+---+---------+
| a | b |    c | d |       e |
+---+---+------+---+---------+
| 1 | a | 1    | 2 |    3    |
| 2 | b | 1    | 2 |    3    |
| 3 | c | 1    | 2 |    3    |
| 4 | d | 1    | 2 |    3    |
+---+---+------+---+---------+

Conclusion: Successfully trimmed the d column.

Example 3: Multiple columns
1
>>> trim_spaces_from_columns(df, ["c", "d"]).show()
Terminal
+---+---+---+---+---------+
| a | b | c | d |       e |
+---+---+---+---+---------+
| 1 | a | 1 | 2 |    3    |
| 2 | b | 1 | 2 |    3    |
| 3 | c | 1 | 2 |    3    |
| 4 | d | 1 | 2 |    3    |
+---+---+---+---+---------+

Conclusion: Successfully trimmed the c and d columns.

Example 4: All columns
1
>>> trim_spaces_from_columns(df, "all").show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 2 | 3 |
| 2 | b | 1 | 2 | 3 |
| 3 | c | 1 | 2 | 3 |
| 4 | d | 1 | 2 | 3 |
+---+---+---+---+---+

Conclusion: Successfully trimmed all columns.

Example 5: Default config
1
>>> trim_spaces_from_columns(df).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
| 1 | a | 1 | 2 | 3 |
| 2 | b | 1 | 2 | 3 |
| 3 | c | 1 | 2 | 3 |
| 4 | d | 1 | 2 | 3 |
+---+---+---+---+---+

Conclusion: Successfully trimmed all columns.

Example 6: Invalid column
1
>>> trim_spaces_from_columns(df, ["f"])
Terminal
ColumnDoesNotExistError: Columns ['f'] do not exist in the DataFrame.
Try one of: ["a", "b", "c", "d", "e"]

Conclusion: Columns do not exist.

Notes
Justification
  • The main reason for this function is because when the data was exported from the Legacy WMS's, there's a whole bunch of trailing spaces in the data fields. My theory is because of the data type in the source system. That is, if it's originally stored as 'char' type, then it will maintain the data length. This issues doesn't seem to be affecting the varchar fields. Nonetheless, this function will strip the white spaces from the data; thus reducing the total size of the data stored therein.
  • The reason why it is necessary to write this out as a custom function, instead of using the F.trim() function from the PySpark library directly is due to the deficiencies of the Java trim() function. More specifically, there are 13 different whitespace characters available in our ascii character set. The Java function only cleans about 6 of these. So therefore, we define this function which iterates through all 13 whitespace characters, and formats them in to a regular expression, to then parse it to the F.regexp_replace() function to be replaced with an empty string (""). Therefore, all 13 characters will be replaced, the strings will be cleaned and trimmed ready for further processing.
  • The reason why this function exists as a standalone, and does not call trim_spaces_from_column() from within a loop is because trim_spaces_from_column() utilises the .withColumn() method to implement the F.regexp_replace() function on columns individually. When implemented iteratively, this process will create huge DAG's for the RDD, and blow out the complexity to a huge extend. Whereas this trim_spaces_from_columns() function will utilise the .withColumns() method to implement the F.regexp_replace() function over all columns at once. This .withColumns() method projects the function down to the underlying dataset in one single execution; not a different execution per column. Therefore, it is more simpler and more efficient.
Regex definition: ^[...]+|[...]+$
  • 1st Alternative: ^[...]+
    • ^ asserts position at start of a line
    • Match a single character present in the list below [...]
      • + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
      • matches a single character in the list (case sensitive)
        • matches the character with index 160 (A0 or 240) literally (case sensitive)
        • matches the character with index 32 (20 or 40) literally (case sensitive)
        • ... (repeat for all whitespace characters)
  • 2nd Alternative: [...]+$
    • Match a single character present in the list below [...]
      • + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
      • matches a single character in the list (case sensitive)
        • matches the character with index 160 (A0 or 240) literally (case sensitive)
        • matches the character with index 32 (20 or 40) literally (case sensitive)
        • ... (repeat for all whitespace characters)
See Also
Source code in src/toolbox_pyspark/cleaning.py
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
@typechecked
def trim_spaces_from_columns(
    dataframe: psDataFrame,
    columns: Optional[Union[str, str_collection]] = None,
) -> psDataFrame:
    """
    !!! note "Summary"
        For a given list of columns, trim all of the excess white spaces from them.

    Params:
        dataframe (psDataFrame):
            The DataFrame to be updated.
        columns (Optional[Union[str, str_collection]], optional):
            The list of columns to be updated.
            Must be valid columns on `dataframe`.
            If given as a string, will be executed as a single column (ie. one-element long list).
            If not given, will apply to all columns in `dataframe` which have the data-type `string`.
            It is also possible to parse the values `#!py "all"` or `#!py "all_string"`, which will also apply this function to all columns in `dataframe` which have the data-type `string`.<br>
            Defaults to `#!py None`.

    Returns:
        (psDataFrame):
            The updated DataFrame.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import trim_spaces_from_columns
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [1, 2, 3, 4],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": ["1   ", "1   ", "1   ", "1   "],
        ...             "d": ["   2", "   2", "   2", "   2"],
        ...             "e": ["   3   ", "   3   ", "   3   ", "   3   "],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Check
        ```{.py .python linenums="1" title="Check"}
        >>> df.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+------+------+---------+
        | a | b |    c |    d |       e |
        +---+---+------+------+---------+
        | 1 | a | 1    |    2 |    3    |
        | 2 | b | 1    |    2 |    3    |
        | 3 | c | 1    |    2 |    3    |
        | 4 | d | 1    |    2 |    3    |
        +---+---+------+------+---------+
        ```
        </div>

        ```{.py .python linenums="1" title="Example 1: One column as list"}
        >>> trim_spaces_from_columns(df, ["c"]).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+------+---------+
        | a | b | c |    d |       e |
        +---+---+---+------+---------+
        | 1 | a | 1 |    2 |    3    |
        | 2 | b | 1 |    2 |    3    |
        | 3 | c | 1 |    2 |    3    |
        | 4 | d | 1 |    2 |    3    |
        +---+---+---+------+---------+
        ```
        !!! success "Conclusion: Successfully trimmed the `c` column."
        </div>

        ```{.py .python linenums="1" title="Example 2: Single column as string"}
        >>> trim_spaces_from_columns(df, "d").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+------+---+---------+
        | a | b |    c | d |       e |
        +---+---+------+---+---------+
        | 1 | a | 1    | 2 |    3    |
        | 2 | b | 1    | 2 |    3    |
        | 3 | c | 1    | 2 |    3    |
        | 4 | d | 1    | 2 |    3    |
        +---+---+------+---+---------+
        ```
        !!! success "Conclusion: Successfully trimmed the `d` column."
        </div>

        ```{.py .python linenums="1" title="Example 3: Multiple columns"}
        >>> trim_spaces_from_columns(df, ["c", "d"]).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---------+
        | a | b | c | d |       e |
        +---+---+---+---+---------+
        | 1 | a | 1 | 2 |    3    |
        | 2 | b | 1 | 2 |    3    |
        | 3 | c | 1 | 2 |    3    |
        | 4 | d | 1 | 2 |    3    |
        +---+---+---+---+---------+
        ```
        !!! success "Conclusion: Successfully trimmed the `c` and `d` columns."
        </div>

        ```{.py .python linenums="1" title="Example 4: All columns"}
        >>> trim_spaces_from_columns(df, "all").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 2 | 3 |
        | 2 | b | 1 | 2 | 3 |
        | 3 | c | 1 | 2 | 3 |
        | 4 | d | 1 | 2 | 3 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully trimmed all columns."
        </div>

        ```{.py .python linenums="1" title="Example 5: Default config"}
        >>> trim_spaces_from_columns(df).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | e |
        +---+---+---+---+---+
        | 1 | a | 1 | 2 | 3 |
        | 2 | b | 1 | 2 | 3 |
        | 3 | c | 1 | 2 | 3 |
        | 4 | d | 1 | 2 | 3 |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully trimmed all columns."
        </div>

        ```{.py .python linenums="1" title="Example 6: Invalid column"}
        >>> trim_spaces_from_columns(df, ["f"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Columns ['f'] do not exist in the DataFrame.
        Try one of: ["a", "b", "c", "d", "e"]
        ```
        !!! failure "Conclusion: Columns do not exist."
        </div>

    ???+ info "Notes"

        ???+ info "Justification"
            - The main reason for this function is because when the data was exported from the Legacy WMS's, there's a _whole bunch_ of trailing spaces in the data fields. My theory is because of the data type in the source system. That is, if it's originally stored as 'char' type, then it will maintain the data length. This issues doesn't seem to be affecting the `varchar` fields. Nonetheless, this function will strip the white spaces from the data; thus reducing the total size of the data stored therein.
            - The reason why it is necessary to write this out as a custom function, instead of using the [`F.trim()`][trim] function from the PySpark library directly is due to the deficiencies of the Java [`trim()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#trim) function. More specifically, there are 13 different whitespace characters available in our ascii character set. The Java function only cleans about 6 of these. So therefore, we define this function which iterates through all 13 whitespace characters, and formats them in to a regular expression, to then parse it to the [`F.regexp_replace()`][regexp_replace] function to be replaced with an empty string (`""`). Therefore, all 13 characters will be replaced, the strings will be cleaned and trimmed ready for further processing.
            - The reason why this function exists as a standalone, and does not call [`trim_spaces_from_column()`][toolbox_pyspark.cleaning.trim_spaces_from_column] from within a loop is because [`trim_spaces_from_column()`][toolbox_pyspark.cleaning.trim_spaces_from_column] utilises the [`.withColumn()`][withColumn] method to implement the [`F.regexp_replace()`][regexp_replace] function on columns individually. When implemented iteratively, this process will create huge DAG's for the RDD, and blow out the complexity to a huge extend. Whereas this [`trim_spaces_from_columns()`][toolbox_pyspark.cleaning.trim_spaces_from_columns] function will utilise the [`.withColumns()`][withColumns] method to implement the [`F.regexp_replace()`][regexp_replace] function over all columns at once. This [`.withColumns()`][withColumns] method projects the function down to the underlying dataset in one single execution; not a different execution per column. Therefore, it is more simpler and more efficient.

            [withColumn]: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.withColumn.html
            [withColumns]: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.withColumns.html
            [trim]: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.trim.html
            [regexp_replace]: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.regexp_replace.html

        ???+ info "Regex definition: `^[...]+|[...]+$`"
            - 1st Alternative: `^[...]+`
                - `^` asserts position at start of a line
                - Match a single character present in the list below `[...]`
                    - `+` matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
                    - matches a single character in the list `  ` (case sensitive)
                        - matches the character ` ` with index 160 (A0 or 240) literally (case sensitive)
                        - matches the character ` ` with index 32 (20 or 40) literally (case sensitive)
                        - ... (repeat for all whitespace characters)
            - 2nd Alternative: `[...]+$`
                - Match a single character present in the list below `[...]`
                    - `+` matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
                    - matches a single character in the list `  ` (case sensitive)
                        - matches the character ` ` with index 160 (A0 or 240) literally (case sensitive)
                        - matches the character ` ` with index 32 (20 or 40) literally (case sensitive)
                        - ... (repeat for all whitespace characters)

    ??? tip "See Also"
        - [`trim_spaces_from_column()`][toolbox_pyspark.cleaning.trim_spaces_from_column]
        - [`ALL_WHITESPACE_CHARACTERS`][toolbox_pyspark.constants.ALL_WHITESPACE_CHARACTERS]
    """
    columns = get_columns(dataframe, columns)
    assert_columns_exists(dataframe=dataframe, columns=columns, match_case=True)
    space_chars: str_list = WHITESPACES.to_list("chr")  # type:ignore
    regexp: str = f"^[{''.join(space_chars)}]+|[{''.join(space_chars)}]+$"
    cols_exprs: dict[str, Column] = {col: F.regexp_replace(col, regexp, "") for col in columns}
    return dataframe.withColumns(cols_exprs)

apply_function_to_column 🔗

apply_function_to_column(
    dataframe: psDataFrame,
    column: str,
    function: str = "upper",
    *function_args,
    **function_kwargs
) -> psDataFrame

Summary

Apply a given PySpark function to a single column on dataframe.

Details

Under the hood, this function will simply call the .withColumn() method to apply the function named in function from the PySpark functions module.

return dataframe.withColumn(column, getattr(F, function)(column, *function_args, **function_kwargs))

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to update.

required
column str

The column to update.

required
function str

The function to execute. Must be a valid function from the PySpark functions module.
Defaults to "upper".

'upper'
*function_args Any

The arguments to push down to the underlying function.

()
**function_kwargs Any

The keyword arguments to push down to the underlying function.

{}

Returns:

Type Description
DataFrame

The updated DataFrame.

Examples

Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import apply_function_to_column
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [0, 1, 2, 3],
...             "b": ["a", "b", "c", "d"],
...             "c": ["c", "c", "c", "c"],
...             "d": ["d", "d", "d", "d"],
...         }
...     )
... )
>>>
>>> # Check
```{.py .python linenums="1" title="Check"}
>>> df.show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | a | c | d |
| 1 | b | c | d |
| 2 | c | c | d |
| 3 | d | c | d |
+---+---+---+---+

Example 1: Default params
1
>>> apply_function_to_column(df, "c").show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | a | C | d |
| 1 | b | C | d |
| 2 | c | C | d |
| 3 | d | C | d |
+---+---+---+---+

Conclusion: Successfully applied the upper function to the c column.

Example 2: Simple function
1
>>> apply_function_to_column(df, "c", "lower").show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | a | c | d |
| 1 | b | c | d |
| 2 | c | c | d |
| 3 | d | c | d |
+---+---+---+---+

Conclusion: Successfully applied the lower function to the c column.

Example 3: Complex function, using args
1
>>> apply_function_to_column(df, "d", "lpad", 5, "?").show()
Terminal
+---+---+---+-------+
| a | b | c |     d |
+---+---+---+-------+
| 0 | a | c | ????d |
| 1 | b | c | ????d |
| 2 | c | c | ????d |
| 3 | d | c | ????d |
+---+---+---+-------+

Conclusion: Successfully applied the lpad function to the d column.

Example 4: Complex function, using kwargs
1
2
3
4
5
6
7
>>> new_df = apply_function_to_column(
...     dataframe=df,
...     column="d",
...     function="lpad",
...     len=5,
...     pad="?",
... ).show()
Terminal
+---+---+---+-------+
| a | b | c |     d |
+---+---+---+-------+
| 0 | a | c | ????d |
| 1 | b | c | ????d |
| 2 | c | c | ????d |
| 3 | d | c | ????d |
+---+---+---+-------+

Conclusion: Successfully applied the lpad function to the d column.

Example 5: Different complex function, using kwargs
1
2
3
4
5
6
7
>>> new_df = apply_function_to_column(
...     dataframe=df,
...     column="b",
...     function="regexp_replace",
...     pattern="c",
...     replacement="17",
... ).show()
Terminal
+---+----+---+---+
| a |  b | c | d |
+---+----+---+---+
| 0 |  a | c | d |
| 1 |  b | c | d |
| 2 | 17 | c | d |
| 3 |  d | c | d |
+---+----+---+---+

Conclusion: Successfully applied the regexp_replace function to the b column.

Example 6: Part of pipe
1
2
3
4
5
6
7
>>> new_df = df.transform(
...     func=apply_function_to_column,
...     column="d",
...     function="lpad",
...     len=5,
...     pad="?",
... ).show()
Terminal
+---+---+---+-------+
| a | b | c |     d |
+---+---+---+-------+
| 0 | a | c | ????d |
| 1 | b | c | ????d |
| 2 | c | c | ????d |
| 3 | d | c | ????d |
+---+---+---+-------+

Conclusion: Successfully applied the lpad function to the d column.

Example 7: Column name in different case
1
2
3
4
5
>>> new_df = df.transform(
...     func=apply_function_to_column,
...     column="D",
...     function="upper",
... ).show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | a | c | D |
| 1 | b | c | D |
| 2 | c | c | D |
| 3 | d | c | D |
+---+---+---+---+

Conclusion: Successfully applied the upper function to the D column.

Example 8: Invalid column
1
>>> apply_function_to_column(df, "f")
Terminal
ColumnDoesNotExistError: Column 'f' does not exist in the DataFrame.
Try one of: ["a", "b", "c", "d"]

Conclusion: Column does not exist.

Notes
  • We have to name the function parameter as the full name because when this function is executed as part of a chain (by using the PySpark .transform() method), that one uses the func parameter.
See Also
Source code in src/toolbox_pyspark/cleaning.py
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
@typechecked
def apply_function_to_column(
    dataframe: psDataFrame,
    column: str,
    function: str = "upper",
    *function_args,
    **function_kwargs,
) -> psDataFrame:
    """
    !!! note "Summary"
        Apply a given PySpark `function` to a single `column` on `dataframe`.

    ???+ abstract "Details"
        Under the hood, this function will simply call the [`.withColumn()`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.withColumn.html) method to apply the function named in `function` from the PySpark [`functions`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/functions.html) module.
        ```py
        return dataframe.withColumn(column, getattr(F, function)(column, *function_args, **function_kwargs))
        ```

    Params:
        dataframe (psDataFrame):
            The DataFrame to update.
        column (str):
            The column to update.
        function (str, optional):
            The function to execute. Must be a valid function from the PySpark [`functions`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/functions.html) module.<br>
            Defaults to `#!py "upper"`.
        *function_args (Any, optional):
            The arguments to push down to the underlying `function`.
        **function_kwargs (Any, optional):
            The keyword arguments to push down to the underlying `function`.

    Returns:
        (psDataFrame):
            The updated DataFrame.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import apply_function_to_column
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [0, 1, 2, 3],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": ["c", "c", "c", "c"],
        ...             "d": ["d", "d", "d", "d"],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Check
        ```{.py .python linenums="1" title="Check"}
        >>> df.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | a | c | d |
        | 1 | b | c | d |
        | 2 | c | c | d |
        | 3 | d | c | d |
        +---+---+---+---+
        ```
        </div>

        ```{.py .python linenums="1" title="Example 1: Default params"}
        >>> apply_function_to_column(df, "c").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | a | C | d |
        | 1 | b | C | d |
        | 2 | c | C | d |
        | 3 | d | C | d |
        +---+---+---+---+
        ```
        !!! success "Conclusion: Successfully applied the `upper` function to the `c` column."
        </div>

        ```{.py .python linenums="1" title="Example 2: Simple function"}
        >>> apply_function_to_column(df, "c", "lower").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | a | c | d |
        | 1 | b | c | d |
        | 2 | c | c | d |
        | 3 | d | c | d |
        +---+---+---+---+
        ```
        !!! success "Conclusion: Successfully applied the `lower` function to the `c` column."
        </div>

        ```{.py .python linenums="1" title="Example 3: Complex function, using args"}
        >>> apply_function_to_column(df, "d", "lpad", 5, "?").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+-------+
        | a | b | c |     d |
        +---+---+---+-------+
        | 0 | a | c | ????d |
        | 1 | b | c | ????d |
        | 2 | c | c | ????d |
        | 3 | d | c | ????d |
        +---+---+---+-------+
        ```
        !!! success "Conclusion: Successfully applied the `lpad` function to the `d` column."
        </div>

        ```{.py .python linenums="1" title="Example 4: Complex function, using kwargs"}
        >>> new_df = apply_function_to_column(
        ...     dataframe=df,
        ...     column="d",
        ...     function="lpad",
        ...     len=5,
        ...     pad="?",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+-------+
        | a | b | c |     d |
        +---+---+---+-------+
        | 0 | a | c | ????d |
        | 1 | b | c | ????d |
        | 2 | c | c | ????d |
        | 3 | d | c | ????d |
        +---+---+---+-------+
        ```
        !!! success "Conclusion: Successfully applied the `lpad` function to the `d` column."
        </div>

        ```{.py .python linenums="1" title="Example 5: Different complex function, using kwargs"}
        >>> new_df = apply_function_to_column(
        ...     dataframe=df,
        ...     column="b",
        ...     function="regexp_replace",
        ...     pattern="c",
        ...     replacement="17",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+----+---+---+
        | a |  b | c | d |
        +---+----+---+---+
        | 0 |  a | c | d |
        | 1 |  b | c | d |
        | 2 | 17 | c | d |
        | 3 |  d | c | d |
        +---+----+---+---+
        ```
        !!! success "Conclusion: Successfully applied the `regexp_replace` function to the `b` column."
        </div>

        ```{.py .python linenums="1" title="Example 6: Part of pipe"}
        >>> new_df = df.transform(
        ...     func=apply_function_to_column,
        ...     column="d",
        ...     function="lpad",
        ...     len=5,
        ...     pad="?",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+-------+
        | a | b | c |     d |
        +---+---+---+-------+
        | 0 | a | c | ????d |
        | 1 | b | c | ????d |
        | 2 | c | c | ????d |
        | 3 | d | c | ????d |
        +---+---+---+-------+
        ```
        !!! success "Conclusion: Successfully applied the `lpad` function to the `d` column."
        </div>

        ```{.py .python linenums="1" title="Example 7: Column name in different case"}
        >>> new_df = df.transform(
        ...     func=apply_function_to_column,
        ...     column="D",
        ...     function="upper",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | a | c | D |
        | 1 | b | c | D |
        | 2 | c | c | D |
        | 3 | d | c | D |
        +---+---+---+---+
        ```
        !!! success "Conclusion: Successfully applied the `upper` function to the `D` column."
        </div>

        ```{.py .python linenums="1" title="Example 8: Invalid column"}
        >>> apply_function_to_column(df, "f")
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Column 'f' does not exist in the DataFrame.
        Try one of: ["a", "b", "c", "d"]
        ```
        !!! failure "Conclusion: Column does not exist."
        </div>

    ??? info "Notes"
        - We have to name the `function` parameter as the full name because when this function is executed as part of a chain (by using the PySpark [`.transform()`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.transform.html) method), that one uses the `func` parameter.

    ??? tip "See Also"
        - [`apply_function_to_columns()`][toolbox_pyspark.cleaning.apply_function_to_columns]
    """
    assert_column_exists(dataframe, column, False)
    return dataframe.withColumn(
        colName=column,
        col=getattr(F, function)(column, *function_args, **function_kwargs),
    )

apply_function_to_columns 🔗

apply_function_to_columns(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    function: str = "upper",
    *function_args,
    **function_kwargs
) -> psDataFrame

Summary

Apply a given PySpark function over multiple columns on a given dataframe.

Details

Under the hood, this function will simply call the .withColumns() method to apply the function named in function from the PySpark functions module.

return dataframe.withColumns(
    {column: getattr(F, function)(column, *args, **kwargs) for column in columns}
)

Parameters:

Name Type Description Default
dataframe DataFrame

The DataFrame to update.

required
columns Union[str, str_collection]

The columns to update.

required
function str

The function to use.
Defaults to "upper".

'upper'

Returns:

Type Description
DataFrame

The updated DataFrame.

Examples

Set up
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import apply_function_to_columns
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> df = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [0, 1, 2, 3],
...             "b": ["a", "b", "c", "d"],
...             "c": ["c", "c", "c", "c"],
...             "d": ["d", "d", "d", "d"],
...         }
...     )
... )
>>>
>>> # Check
```{.py .python linenums="1" title="Check"}
>>> df.show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | a | c | d |
| 1 | b | c | d |
| 2 | c | c | d |
| 3 | d | c | d |
+---+---+---+---+

Example 1: Default params
1
>>> apply_function_to_columns(df, ["b", "c"]).show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | A | C | d |
| 1 | B | C | d |
| 2 | C | C | d |
| 3 | D | C | d |
+---+---+---+---+

Conclusion: Successfully applied the upper function to the b and c columns.

Example 2: Simple function
1
>>> apply_function_to_columns(df, ["b", "c"], "lower").show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | a | c | d |
| 1 | b | c | d |
| 2 | c | c | d |
| 3 | d | c | d |
+---+---+---+---+

Conclusion: Successfully applied the lower function to the b and c columns.

Example 3: Complex function, with args
1
>>> apply_function_to_columns(df, ["b", "c", "d"], "lpad", 5, "?").show()
Terminal
+---+-------+-------+-------+
| a |     b |     c |     d |
+---+-------+-------+-------+
| 0 | ????a | ????c | ????d |
| 1 | ????b | ????c | ????d |
| 2 | ????c | ????c | ????d |
| 3 | ????d | ????c | ????d |
+---+-------+-------+-------+

Conclusion: Successfully applied the lpad function to the b, c and d columns.

Example 4: Complex function, with kwargs
1
2
3
4
5
6
7
>>> apply_function_to_columns(
...     dataframe=df,
...     columns=["b", "c", "d"],
...     function="lpad",
...     len=5,
...     pad="?",
... ).show()
Terminal
+---+-------+-------+-------+
| a |     b |     c |     d |
+---+-------+-------+-------+
| 0 | ????a | ????c | ????d |
| 1 | ????b | ????c | ????d |
| 2 | ????c | ????c | ????d |
| 3 | ????d | ????c | ????d |
+---+-------+-------+-------+

Conclusion: Successfully applied the lpad function to the b, c and d columns.

Example 5: Different complex function, with kwargs
1
2
3
4
5
6
7
>>> apply_function_to_columns(
...     dataframe=df,
...     columns=["b", "c", "d"],
...     function="regexp_replace",
...     pattern="c",
...     replacement="17",
... ).show()
Terminal
+---+----+----+---+
| a |  b |  c | d |
+---+----+----+---+
| 0 |  a | 17 | d |
| 1 |  b | 17 | d |
| 2 | 17 | 17 | d |
| 3 |  d | 17 | d |
+---+----+----+---+

Conclusion: Successfully applied the regexp_replace function to the b, c and d columns.

Example 6: Part of pipe
1
2
3
4
5
6
7
>>> df.transform(
...     func=apply_function_to_columns,
...     columns=["b", "c", "d"],
...     function="lpad",
...     len=5,
...     pad="?",
... ).show()
Terminal
+---+-------+-------+-------+
| a |     b |     c |     d |
+---+-------+-------+-------+
| 0 | ????a | ????c | ????d |
| 1 | ????b | ????c | ????d |
| 2 | ????c | ????c | ????d |
| 3 | ????d | ????c | ????d |
+---+-------+-------+-------+

Conclusion: Successfully applied the lpad function to the b, c and d columns.

Example 7: Column name in different case
1
2
3
4
5
>>> apply_function_to_columns(
...     dataframe=df,
...     columns=["B", "c", "D"],
...     function="upper",
... ).show()
Terminal
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 0 | A | C | D |
| 1 | B | C | D |
| 2 | C | C | D |
| 3 | D | C | D |
+---+---+---+---+

Conclusion: Successfully applied the upper function to the B, c and D columns.

Example 8: Invalid columns
1
>>> apply_function_to_columns(df, ["f"])
Terminal
ColumnDoesNotExistError: Columns ['f'] do not exist in the DataFrame.
Try one of: ["a", "b", "c", "d"]

Conclusion: Columns do not exist.

Notes
  • We have to name the function parameter as the full name because when this function is executed as part of a chain (by using the PySpark .transform() method), that one uses the func parameter.
See Also
Source code in src/toolbox_pyspark/cleaning.py
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
@typechecked
def apply_function_to_columns(
    dataframe: psDataFrame,
    columns: Union[str, str_collection],
    function: str = "upper",
    *function_args,
    **function_kwargs,
) -> psDataFrame:
    """
    !!! note "Summary"
        Apply a given PySpark `function` over multiple `columns` on a given `dataframe`.

    ???+ abstract "Details"
        Under the hood, this function will simply call the [`.withColumns()`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.withColumns.html) method to apply the function named in `function` from the PySpark [`functions`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/functions.html) module.
        ```py
        return dataframe.withColumns(
            {column: getattr(F, function)(column, *args, **kwargs) for column in columns}
        )
        ```

    Params:
        dataframe (psDataFrame):
            The DataFrame to update.
        columns (Union[str, str_collection]):
            The columns to update.
        function (str, optional):
            The function to use.<br>
            Defaults to `#!py "upper"`.

    Returns:
        (psDataFrame):
            The updated DataFrame.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import apply_function_to_columns
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> df = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [0, 1, 2, 3],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": ["c", "c", "c", "c"],
        ...             "d": ["d", "d", "d", "d"],
        ...         }
        ...     )
        ... )
        >>>
        >>> # Check
        ```{.py .python linenums="1" title="Check"}
        >>> df.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | a | c | d |
        | 1 | b | c | d |
        | 2 | c | c | d |
        | 3 | d | c | d |
        +---+---+---+---+
        ```
        </div>

        ```{.py .python linenums="1" title="Example 1: Default params"}
        >>> apply_function_to_columns(df, ["b", "c"]).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | A | C | d |
        | 1 | B | C | d |
        | 2 | C | C | d |
        | 3 | D | C | d |
        +---+---+---+---+
        ```
        !!! success "Conclusion: Successfully applied the `upper` function to the `b` and `c` columns."
        </div>

        ```{.py .python linenums="1" title="Example 2: Simple function"}
        >>> apply_function_to_columns(df, ["b", "c"], "lower").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | a | c | d |
        | 1 | b | c | d |
        | 2 | c | c | d |
        | 3 | d | c | d |
        +---+---+---+---+
        ```
        !!! success "Conclusion: Successfully applied the `lower` function to the `b` and `c` columns."
        </div>

        ```{.py .python linenums="1" title="Example 3: Complex function, with args"}
        >>> apply_function_to_columns(df, ["b", "c", "d"], "lpad", 5, "?").show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+-------+-------+-------+
        | a |     b |     c |     d |
        +---+-------+-------+-------+
        | 0 | ????a | ????c | ????d |
        | 1 | ????b | ????c | ????d |
        | 2 | ????c | ????c | ????d |
        | 3 | ????d | ????c | ????d |
        +---+-------+-------+-------+
        ```
        !!! success "Conclusion: Successfully applied the `lpad` function to the `b`, `c` and `d` columns."
        </div>

        ```{.py .python linenums="1" title="Example 4: Complex function, with kwargs"}
        >>> apply_function_to_columns(
        ...     dataframe=df,
        ...     columns=["b", "c", "d"],
        ...     function="lpad",
        ...     len=5,
        ...     pad="?",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+-------+-------+-------+
        | a |     b |     c |     d |
        +---+-------+-------+-------+
        | 0 | ????a | ????c | ????d |
        | 1 | ????b | ????c | ????d |
        | 2 | ????c | ????c | ????d |
        | 3 | ????d | ????c | ????d |
        +---+-------+-------+-------+
        ```
        !!! success "Conclusion: Successfully applied the `lpad` function to the `b`, `c` and `d` columns."
        </div>

        ```{.py .python linenums="1" title="Example 5: Different complex function, with kwargs"}
        >>> apply_function_to_columns(
        ...     dataframe=df,
        ...     columns=["b", "c", "d"],
        ...     function="regexp_replace",
        ...     pattern="c",
        ...     replacement="17",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+----+----+---+
        | a |  b |  c | d |
        +---+----+----+---+
        | 0 |  a | 17 | d |
        | 1 |  b | 17 | d |
        | 2 | 17 | 17 | d |
        | 3 |  d | 17 | d |
        +---+----+----+---+
        ```
        !!! success "Conclusion: Successfully applied the `regexp_replace` function to the `b`, `c` and `d` columns."
        </div>

        ```{.py .python linenums="1" title="Example 6: Part of pipe"}
        >>> df.transform(
        ...     func=apply_function_to_columns,
        ...     columns=["b", "c", "d"],
        ...     function="lpad",
        ...     len=5,
        ...     pad="?",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+-------+-------+-------+
        | a |     b |     c |     d |
        +---+-------+-------+-------+
        | 0 | ????a | ????c | ????d |
        | 1 | ????b | ????c | ????d |
        | 2 | ????c | ????c | ????d |
        | 3 | ????d | ????c | ????d |
        +---+-------+-------+-------+
        ```
        !!! success "Conclusion: Successfully applied the `lpad` function to the `b`, `c` and `d` columns."
        </div>

        ```{.py .python linenums="1" title="Example 7: Column name in different case"}
        >>> apply_function_to_columns(
        ...     dataframe=df,
        ...     columns=["B", "c", "D"],
        ...     function="upper",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+
        | a | b | c | d |
        +---+---+---+---+
        | 0 | A | C | D |
        | 1 | B | C | D |
        | 2 | C | C | D |
        | 3 | D | C | D |
        +---+---+---+---+
        ```
        !!! success "Conclusion: Successfully applied the `upper` function to the `B`, `c` and `D` columns."
        </div>

        ```{.py .python linenums="1" title="Example 8: Invalid columns"}
        >>> apply_function_to_columns(df, ["f"])
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Columns ['f'] do not exist in the DataFrame.
        Try one of: ["a", "b", "c", "d"]
        ```
        !!! failure "Conclusion: Columns do not exist."
        </div>

    ??? info "Notes"
        - We have to name the `function` parameter as the full name because when this function is executed as part of a chain (by using the PySpark [`.transform()`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.transform.html) method), that one uses the `func` parameter.

    ??? tip "See Also"
        - [`apply_function_to_column()`][toolbox_pyspark.cleaning.apply_function_to_column]
    """
    columns = get_columns(dataframe, columns)
    assert_columns_exists(dataframe, columns, False)
    return dataframe.withColumns(
        {
            column: getattr(F, function)(column, *function_args, **function_kwargs)
            for column in columns
        }
    )

drop_matching_rows 🔗

drop_matching_rows(
    left_table: psDataFrame,
    right_table: psDataFrame,
    on_keys: Union[str, str_collection],
    join_type: VALID_PYAPARK_JOIN_TYPES = "left_anti",
    where_clause: Optional[str] = None,
) -> psDataFrame

Summary

This function is designed to remove any rows on the left_table which are existing on the right_table. That's why the join_type should always be left_anti.

Details

The intention behind this function is originating from the Accumulation layer in the BigDaS environment. The process on this table layer is to only insert rows from the left_table to the right_table with are not existing on the right_table. We include the where_clause here so that we can control any updated rows. Specifically, we check the editdatetime field between the left_table and the right_table, and any record on the left_table where the editdatetime field is greater than the editdatetime value on the right_table, then this row will remain on the left_table, and will later be updated on the right_table.

It's important to specify here that this function was created to handle the same table between the left_table and the right_table, which are existing between different layers in the ADLS environment. Logically, it can be used for other purposes (it's generic enough); however, the intention was specifically for cleaning during the data pipeline processes.

Parameters:

Name Type Description Default
left_table DataFrame

The DataFrame from which you will be deleting the records.

required
right_table DataFrame

The DataFrame from which to check for existing records. If any matching on_keys are existing on both the right_table and the left_table, then those records will be deleted from the left_table.

required
on_keys Union[str, str_collection]

The matching keys between the two tables. These keys (aka columns) must be existing on both the left_table and the right_table.

required
join_type VALID_PYAPARK_JOIN_TYPES

The type of join to use for this process. For the best performance, keep it as the default value.
Defaults to "left_anti".

'left_anti'
where_clause Optional[str]

Any additional conditions to place on this join. Any records which match this condition will be kept on the left_table.
Defaults to None.

None

Returns:

Type Description
DataFrame

The left_table after it has had it's rows deleted and cleaned by the right_table.

Examples

Set up
 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
>>> # Imports
>>> import pandas as pd
>>> from pyspark.sql import SparkSession
>>> from toolbox_pyspark.cleaning import drop_matching_rows
>>>
>>> # Instantiate Spark
>>> spark = SparkSession.builder.getOrCreate()
>>>
>>> # Create data
>>> left = spark.createDataFrame(
...     pd.DataFrame(
...         {
...             "a": [0, 1, 2, 3],
...             "b": ["a", "b", "c", "d"],
...             "c": [1, 1, 1, 1],
...             "d": ["2", "2", "2", "2"],
...             "n": ["a", "b", "c", "d"],
...         }
...     )
... )
... right = left.where("a in ("1", "2")")
>>>
>>> # Check
```{.py .python linenums="1" title="Check"}
>>> left.show()
>>> right.show()
Terminal
+---+---+---+---+---+
| a | b | c | d | n |
+---+---+---+---+---+
| 1 | a | 1 | 2 | a |
| 2 | b | 1 | 2 | b |
| 3 | c | 1 | 2 | c |
| 4 | d | 1 | 2 | d |
+---+---+---+---+---+
Terminal
+---+---+---+---+---+
| a | b | c | d | n |
+---+---+---+---+---+
| 1 | a | 1 | 2 | a |
| 2 | b | 1 | 2 | b |
+---+---+---+---+---+

Example 1: Single column
1
2
3
4
5
>>> drop_matching_rows(
...     left_table=left,
...     right_table=right,
...     on_keys=["a"],
... ).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | n |
+---+---+---+---+---+
| 3 | c | 1 | 2 | c |
| 4 | d | 1 | 2 | d |
+---+---+---+---+---+

Conclusion: Successfully removed the records from the left_table which are existing on the right_table.

Example 2: Single column as string
1
2
3
4
5
>>> left.transform(
...     drop_matching_rows,
...     right_table=right,
...     on_keys="a",
... ).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | n |
+---+---+---+---+---+
| 3 | c | 1 | 2 | c |
| 4 | d | 1 | 2 | d |
+---+---+---+---+---+

Conclusion: Successfully removed the records from the left_table which are existing on the right_table.

Example 3: Multiple key columns
1
2
3
4
5
>>> drop_matching_rows(
...     left_table=left,
...     right_table=right,
...     on_keys=["a", "b"],
... ).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | n |
+---+---+---+---+---+
| 3 | c | 1 | 2 | c |
| 4 | d | 1 | 2 | d |
+---+---+---+---+---+

Conclusion: Successfully removed the records from the left_table which are existing on the right_table.

Example 4: Including `where` clause
1
2
3
4
5
6
>>> drop_matching_rows(
...     left_table=left,
...     right_table=right,
...     on_keys=["a"],
...     where_clause="n <> 'd'",
... ).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | n |
+---+---+---+---+---+
| 3 | c | 1 | 2 | c |
+---+---+---+---+---+

Conclusion: Successfully removed the records from the left_table which are existing on the right_table and matched the where clause.

Example 5: Part of pipe
1
2
3
4
5
>>> left.transform(
...     func=drop_matching_rows,
...     right_table=right,
...     on_keys=["a"],
... ).show()
Terminal
+---+---+---+---+---+
| a | b | c | d | n |
+---+---+---+---+---+
| 3 | c | 1 | 2 | c |
| 4 | d | 1 | 2 | d |
+---+---+---+---+---+

Conclusion: Successfully removed the records from the left_table which are existing on the right_table.

Example 6: Invalid column
1
2
3
4
5
>>> drop_matching_rows(
...     left_table=left,
...     right_table=right,
...     on_keys=["f"],
... )
Terminal
ColumnDoesNotExistError: Columns ['f'] do not exist in the DataFrame.
Try one of: ["a", "b", "c", "d", "n"]

Conclusion: Columns do not exist.

Notes
  • The on_keys parameter can be a single string or a list of strings. This is to allow for multiple columns to be used as the matching keys.
  • The where_clause parameter is optional. If specified, then only the records which match the condition will be kept on the left_table. It is applied after the join. If not specified, then all records which are existing on the right_table will be removed from the left_table.
See Also
Source code in src/toolbox_pyspark/cleaning.py
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
@typechecked
def drop_matching_rows(
    left_table: psDataFrame,
    right_table: psDataFrame,
    on_keys: Union[str, str_collection],
    join_type: VALID_PYAPARK_JOIN_TYPES = "left_anti",
    where_clause: Optional[str] = None,
) -> psDataFrame:
    """
    !!! note "Summary"
        This function is designed to _remove_ any rows on the `left_table` which _are_ existing on the `right_table`. That's why the `join_type` should always be `left_anti`.

    ???+ abstract "Details"
        The intention behind this function is originating from the `Accumulation` layer in the BigDaS environment. The process on this table layer is to only _insert_ rows from the `left_table` to the `right_table` with are **not existing** on the `right_table`. We include the `where_clause` here so that we can control any updated rows. Specifically, we check the `editdatetime` field between the `left_table` and the `right_table`, and any record on the `left_table` where the `editdatetime` field is _greater than_ the `editdatetime` value on the `right_table`, then this row will _remain_ on the `left_table`, and will later be _updated_ on the `right_table`.

        It's important to specify here that this function was created to handle the _same table_ between the `left_table` and the `right_table`, which are existing between different layers in the ADLS environment. Logically, it can be used for other purposes (it's generic enough); however, the intention was specifically for cleaning during the data pipeline processes.

    Params:
        left_table (psDataFrame):
            The DataFrame _from which_ you will be deleting the records.
        right_table (psDataFrame):
            The DataFrame _from which_ to check for existing records. If any matching `on_keys` are existing on both the `right_table` and the `left_table`, then those records will be deleted from the `left_table`.
        on_keys (Union[str, str_collection]):
            The matching keys between the two tables. These keys (aka columns) must be existing on both the `left_table` and the `right_table`.
        join_type (VALID_PYAPARK_JOIN_TYPES, optional):
            The type of join to use for this process. For the best performance, keep it as the default value.<br>
            Defaults to `#!py "left_anti"`.
        where_clause (Optional[str], optional):
            Any additional conditions to place on this join. Any records which **match** this condition will be **kept** on the `left_table`.<br>
            Defaults to `#!py None`.

    Returns:
        (psDataFrame):
            The `left_table` after it has had it's rows deleted and cleaned by the `right_table`.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        >>> # Imports
        >>> import pandas as pd
        >>> from pyspark.sql import SparkSession
        >>> from toolbox_pyspark.cleaning import drop_matching_rows
        >>>
        >>> # Instantiate Spark
        >>> spark = SparkSession.builder.getOrCreate()
        >>>
        >>> # Create data
        >>> left = spark.createDataFrame(
        ...     pd.DataFrame(
        ...         {
        ...             "a": [0, 1, 2, 3],
        ...             "b": ["a", "b", "c", "d"],
        ...             "c": [1, 1, 1, 1],
        ...             "d": ["2", "2", "2", "2"],
        ...             "n": ["a", "b", "c", "d"],
        ...         }
        ...     )
        ... )
        ... right = left.where("a in ("1", "2")")
        >>>
        >>> # Check
        ```{.py .python linenums="1" title="Check"}
        >>> left.show()
        >>> right.show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | n |
        +---+---+---+---+---+
        | 1 | a | 1 | 2 | a |
        | 2 | b | 1 | 2 | b |
        | 3 | c | 1 | 2 | c |
        | 4 | d | 1 | 2 | d |
        +---+---+---+---+---+
        ```
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | n |
        +---+---+---+---+---+
        | 1 | a | 1 | 2 | a |
        | 2 | b | 1 | 2 | b |
        +---+---+---+---+---+
        ```
        </div>

        ```{.py .python linenums="1" title="Example 1: Single column"}
        >>> drop_matching_rows(
        ...     left_table=left,
        ...     right_table=right,
        ...     on_keys=["a"],
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | n |
        +---+---+---+---+---+
        | 3 | c | 1 | 2 | c |
        | 4 | d | 1 | 2 | d |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully removed the records from the `left_table` which are existing on the `right_table`."
        </div>

        ```{.py .python linenums="1" title="Example 2: Single column as string"}
        >>> left.transform(
        ...     drop_matching_rows,
        ...     right_table=right,
        ...     on_keys="a",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | n |
        +---+---+---+---+---+
        | 3 | c | 1 | 2 | c |
        | 4 | d | 1 | 2 | d |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully removed the records from the `left_table` which are existing on the `right_table`."
        </div>

        ```{.py .python linenums="1" title="Example 3: Multiple key columns"}
        >>> drop_matching_rows(
        ...     left_table=left,
        ...     right_table=right,
        ...     on_keys=["a", "b"],
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | n |
        +---+---+---+---+---+
        | 3 | c | 1 | 2 | c |
        | 4 | d | 1 | 2 | d |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully removed the records from the `left_table` which are existing on the `right_table`."
        </div>

        ```{.py .python linenums="1" title="Example 4: Including `where` clause"}
        >>> drop_matching_rows(
        ...     left_table=left,
        ...     right_table=right,
        ...     on_keys=["a"],
        ...     where_clause="n <> 'd'",
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | n |
        +---+---+---+---+---+
        | 3 | c | 1 | 2 | c |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully removed the records from the `left_table` which are existing on the `right_table` and matched the `where` clause."
        </div>

        ```{.py .python linenums="1" title="Example 5: Part of pipe"}
        >>> left.transform(
        ...     func=drop_matching_rows,
        ...     right_table=right,
        ...     on_keys=["a"],
        ... ).show()
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        +---+---+---+---+---+
        | a | b | c | d | n |
        +---+---+---+---+---+
        | 3 | c | 1 | 2 | c |
        | 4 | d | 1 | 2 | d |
        +---+---+---+---+---+
        ```
        !!! success "Conclusion: Successfully removed the records from the `left_table` which are existing on the `right_table`."
        </div>

        ```{.py .python linenums="1" title="Example 6: Invalid column"}
        >>> drop_matching_rows(
        ...     left_table=left,
        ...     right_table=right,
        ...     on_keys=["f"],
        ... )
        ```
        <div class="result" markdown>
        ```{.txt .text title="Terminal"}
        ColumnDoesNotExistError: Columns ['f'] do not exist in the DataFrame.
        Try one of: ["a", "b", "c", "d", "n"]
        ```
        !!! failure "Conclusion: Columns do not exist."
        </div>

    ??? info "Notes"
        - The `on_keys` parameter can be a single string or a list of strings. This is to allow for multiple columns to be used as the matching keys.
        - The `where_clause` parameter is optional. If specified, then only the records which match the condition will be kept on the `left_table`. It is applied after the join. If not specified, then all records which are existing on the `right_table` will be removed from the `left_table`.

    ??? tip "See Also"
        - [`assert_columns_exists()`][toolbox_pyspark.checks.assert_columns_exists]
    """
    on_keys = [on_keys] if is_type(on_keys, str) else on_keys
    assert_columns_exists(left_table, on_keys, False)
    assert_columns_exists(right_table, on_keys, False)
    return (
        left_table.alias("left")
        .join(right_table.alias("right"), on=on_keys, how=join_type)
        .where("1=1" if where_clause is None else where_clause)
        .select([f"left.{col}" for col in left_table.columns])
    )