Skip to content

spark_frame.data_diff

This module contains a the method compare_dataframes which is used to compare two DataFrames. It generates a DiffResult object, which can be used to display the results on stdout or even be exported as an interactive HTML report file. For more advanced use cases, the underlying results can also be accessed as DataFrames.


compare_dataframes(left_df: DataFrame, right_df: DataFrame, join_cols: Optional[List[str]] = None) -> DiffResult

Compares two DataFrames and return a DiffResult object.

We first compare the DataFrame schemas. If the schemas are different, we adapt the DataFrames to make them as much comparable as possible: - If the order of the columns changed, we re-order them automatically to perform the diff - If the order of the fields inside a struct changed, we re-order them automatically to perform the diff - If a column type changed, we cast the column to the smallest common type - We don't recognize when a column is renamed, we treat it as if the old column was removed and the new column added

If join_cols is specified, we will use the specified columns to perform the comparison join between the two DataFrames. Ideally, the join_cols should respect an unicity constraint.

If they contain duplicates, a safety check is performed to prevent a potential combinatorial explosion: if the number of rows in the joined DataFrame would be more than twice the size of the original DataFrames, then an Exception is raised and the user will be asked to provide another set of join_cols.

If no join_cols is specified, the algorithm will try to automatically find a single column suitable for the join. However, the automatic inference can only find join keys based on a single column. If the DataFrame's unique keys are composite (multiple columns) they must be given explicitly via join_cols to perform the diff analysis.

Tips

  • If you want to test a column renaming, you can temporarily add renaming steps to the DataFrame you want to test.
  • If you want to exclude columns from the diff, you can simply drop them from the DataFrames you want to compare.
  • When comparing arrays, this algorithm ignores their ordering (e.g. [1, 2, 3] == [3, 2, 1]).
  • When dealing with a nested structure, if the struct contains a unique identifier, it can be specified in the join_cols and the structure will be automatically unnested in the diff results. For instance, if we have a structure my_array: ARRAY<STRUCT<a, b, ...>> and if a is a unique identifier, then you can add "my_array!.a" in the join_cols argument. (cf. Example 2)

Parameters:

Name Type Description Default
left_df DataFrame

A Spark DataFrame

required
right_df DataFrame

Another DataFrame

required
join_cols Optional[List[str]]

Specifies the columns on which the two DataFrames should be joined to compare them

None

Returns:

Type Description
DiffResult

A DiffResult object

Example 1: simple diff

>>> from spark_frame.data_diff.compare_dataframes_impl import __get_test_dfs
>>> from spark_frame.data_diff import compare_dataframes
>>> df1, df2 = __get_test_dfs()
>>> df1.show()
+---+-----------+
| id|   my_array|
+---+-----------+
|  1|[{1, 2, 3}]|
|  2|[{1, 2, 3}]|
|  3|[{1, 2, 3}]|
+---+-----------+
>>> df2.show()
+---+--------------+
| id|      my_array|
+---+--------------+
|  1|[{1, 2, 3, 4}]|
|  2|[{2, 2, 3, 4}]|
|  4|[{1, 2, 3, 4}]|
+---+--------------+
>>> diff_result = compare_dataframes(df1, df2)

Analyzing differences...
No join_cols provided: trying to automatically infer a column that can be used for joining the two DataFrames
Found the following column: id
Generating the diff by joining the DataFrames together using the inferred column: id
>>> diff_result.display()
Schema has changed:
@@ -1,2 +1,2 @@

 id INT
-my_array ARRAY<STRUCT<a:INT,b:INT,c:INT>>
+my_array ARRAY<STRUCT<a:INT,b:INT,c:INT,d:INT>>
WARNING: columns that do not match both sides will be ignored

diff NOT ok

Row count ok: 3 rows

0 (0.0%) rows are identical
2 (50.0%) rows have changed
1 (25.0%) rows are only in 'left'
1 (25.0%) rows are only in 'right

Found the following changes:
+-----------+-------------+---------------------+---------------------------+--------------+
|column_name|total_nb_diff|left_value           |right_value                |nb_differences|
+-----------+-------------+---------------------+---------------------------+--------------+
|my_array   |2            |[{"a":1,"b":2,"c":3}]|[{"a":1,"b":2,"c":3,"d":4}]|1             |
|my_array   |2            |[{"a":1,"b":2,"c":3}]|[{"a":2,"b":2,"c":3,"d":4}]|1             |
+-----------+-------------+---------------------+---------------------------+--------------+

1 rows were only found in 'left' :
Most frequent values in 'left' for each column :
+-----------+---------------------+---+
|column_name|value                |nb |
+-----------+---------------------+---+
|id         |3                    |1  |
|my_array   |[{"a":1,"b":2,"c":3}]|1  |
+-----------+---------------------+---+

1 rows were only found in 'right' :
Most frequent values in 'right' for each column :
+-----------+---------------------------+---+
|column_name|value                      |nb |
+-----------+---------------------------+---+
|id         |4                          |1  |
|my_array   |[{"a":1,"b":2,"c":3,"d":4}]|1  |
+-----------+---------------------------+---+
>>> diff_result.export_to_html(output_file_path="test_working_dir/compare_dataframes_example_1.html")
Report exported as test_working_dir/compare_dataframes_example_1.html

Check out the exported report here

Example 2: diff on complex structures

By adding "my_array!.a" to the join_cols argument, the array gets unnested for the diff

>>> diff_result_unnested = compare_dataframes(df1, df2, join_cols=["id", "my_array!.a"])

Analyzing differences...
Generating the diff by joining the DataFrames together using the provided column: id
Generating the diff by joining the DataFrames together using the provided columns: ['id', 'my_array!.a']
>>> diff_result_unnested.display()
Schema has changed:
@@ -1,4 +1,5 @@

 id INT
 my_array!.a INT
 my_array!.b INT
 my_array!.c INT
+my_array!.d INT
WARNING: columns that do not match both sides will be ignored

diff NOT ok

WARNING: This diff has multiple granularity levels, we will print the results for each granularity level,
         but we recommend to export the results to html for a much more digest result.

##############################################################
Granularity : root (4 rows)

Row count ok: 3 rows

2 (50.0%) rows are identical
0 (0.0%) rows have changed
1 (25.0%) rows are only in 'left'
1 (25.0%) rows are only in 'right

1 rows were only found in 'left' :
Most frequent values in 'left' for each column :
+-----------+-----+---+
|column_name|value|nb |
+-----------+-----+---+
|id         |3    |1  |
|my_array!.a|1    |2  |
|my_array!.b|2    |2  |
|my_array!.c|3    |2  |
+-----------+-----+---+

1 rows were only found in 'right' :
Most frequent values in 'right' for each column :
+-----------+-----+---+
|column_name|value|nb |
+-----------+-----+---+
|id         |4    |1  |
|my_array!.a|1    |1  |
|my_array!.a|2    |1  |
|my_array!.b|2    |2  |
|my_array!.c|3    |2  |
|my_array!.d|4    |3  |
+-----------+-----+---+

##############################################################
Granularity : my_array! (5 rows)

Row count ok: 3 rows

1 (20.0%) rows are identical
0 (0.0%) rows have changed
2 (40.0%) rows are only in 'left'
2 (40.0%) rows are only in 'right

2 rows were only found in 'left' :
Most frequent values in 'left' for each column :
+-----------+-----+---+
|column_name|value|nb |
+-----------+-----+---+
|id         |3    |1  |
|my_array!.a|1    |2  |
|my_array!.b|2    |2  |
|my_array!.c|3    |2  |
+-----------+-----+---+

2 rows were only found in 'right' :
Most frequent values in 'right' for each column :
+-----------+-----+---+
|column_name|value|nb |
+-----------+-----+---+
|id         |4    |1  |
|my_array!.a|1    |1  |
|my_array!.a|2    |1  |
|my_array!.b|2    |2  |
|my_array!.c|3    |2  |
|my_array!.d|4    |3  |
+-----------+-----+---+
>>> diff_result_unnested.export_to_html(output_file_path="test_working_dir/compare_dataframes_example_2.html")
Report exported as test_working_dir/compare_dataframes_example_2.html

Check out the exported report here

Source code in spark_frame/data_diff/compare_dataframes_impl.py
def compare_dataframes(
    left_df: DataFrame,
    right_df: DataFrame,
    join_cols: Optional[List[str]] = None,
) -> DiffResult:
    """Compares two DataFrames and return a [`DiffResult`][spark_frame.data_diff.diff_result.DiffResult] object.

    We first compare the DataFrame schemas. If the schemas are different, we adapt the DataFrames to make them
    as much comparable as possible:
    - If the order of the columns changed, we re-order them automatically to perform the diff
    - If the order of the fields inside a struct changed, we re-order them automatically to perform the diff
    - If a column type changed, we cast the column to the smallest common type
    - We don't recognize when a column is renamed, we treat it as if the old column was removed and the new column added

    If `join_cols` is specified, we will use the specified columns to perform the comparison join between the
    two DataFrames. Ideally, the `join_cols` should respect an unicity constraint.

    If they contain duplicates, a safety check is performed to prevent a potential combinatorial explosion:
    if the number of rows in the joined DataFrame would be more than twice the size of the original DataFrames,
    then an Exception is raised and the user will be asked to provide another set of `join_cols`.

    If no `join_cols` is specified, the algorithm will try to automatically find a single column suitable for
    the join. However, the automatic inference can only find join keys based on a single column.
    If the DataFrame's unique keys are composite (multiple columns) they must be given explicitly via `join_cols`
    to perform the diff analysis.

    !!! tip "Tips"
        - If you want to test a column renaming, you can temporarily add renaming steps to the DataFrame
          you want to test.
        - If you want to exclude columns from the diff, you can simply drop them from the DataFrames you want to
          compare.
        - When comparing arrays, this algorithm ignores their ordering (e.g. `[1, 2, 3] == [3, 2, 1]`).
        - When dealing with a nested structure, if the struct contains a unique identifier, it can be specified
          in the join_cols and the structure will be automatically unnested in the diff results.
          For instance, if we have a structure `my_array: ARRAY<STRUCT<a, b, ...>>`
          and if `a` is a unique identifier, then you can add `"my_array!.a"` in the join_cols argument.
          (cf. Example 2)

    Args:
        left_df: A Spark DataFrame
        right_df: Another DataFrame
        join_cols: Specifies the columns on which the two DataFrames should be joined to compare them

    Returns:
        A DiffResult object

    Examples: Example 1: simple diff
        >>> from spark_frame.data_diff.compare_dataframes_impl import __get_test_dfs
        >>> from spark_frame.data_diff import compare_dataframes
        >>> df1, df2 = __get_test_dfs()

        >>> df1.show()
        +---+-----------+
        | id|   my_array|
        +---+-----------+
        |  1|[{1, 2, 3}]|
        |  2|[{1, 2, 3}]|
        |  3|[{1, 2, 3}]|
        +---+-----------+
        <BLANKLINE>

        >>> df2.show()
        +---+--------------+
        | id|      my_array|
        +---+--------------+
        |  1|[{1, 2, 3, 4}]|
        |  2|[{2, 2, 3, 4}]|
        |  4|[{1, 2, 3, 4}]|
        +---+--------------+
        <BLANKLINE>

        >>> diff_result = compare_dataframes(df1, df2)
        <BLANKLINE>
        Analyzing differences...
        No join_cols provided: trying to automatically infer a column that can be used for joining the two DataFrames
        Found the following column: id
        Generating the diff by joining the DataFrames together using the inferred column: id

        >>> diff_result.display()
        Schema has changed:
        @@ -1,2 +1,2 @@
        <BLANKLINE>
         id INT
        -my_array ARRAY<STRUCT<a:INT,b:INT,c:INT>>
        +my_array ARRAY<STRUCT<a:INT,b:INT,c:INT,d:INT>>
        WARNING: columns that do not match both sides will be ignored
        <BLANKLINE>
        diff NOT ok
        <BLANKLINE>
        Row count ok: 3 rows
        <BLANKLINE>
        0 (0.0%) rows are identical
        2 (50.0%) rows have changed
        1 (25.0%) rows are only in 'left'
        1 (25.0%) rows are only in 'right
        <BLANKLINE>
        Found the following changes:
        +-----------+-------------+---------------------+---------------------------+--------------+
        |column_name|total_nb_diff|left_value           |right_value                |nb_differences|
        +-----------+-------------+---------------------+---------------------------+--------------+
        |my_array   |2            |[{"a":1,"b":2,"c":3}]|[{"a":1,"b":2,"c":3,"d":4}]|1             |
        |my_array   |2            |[{"a":1,"b":2,"c":3}]|[{"a":2,"b":2,"c":3,"d":4}]|1             |
        +-----------+-------------+---------------------+---------------------------+--------------+
        <BLANKLINE>
        1 rows were only found in 'left' :
        Most frequent values in 'left' for each column :
        +-----------+---------------------+---+
        |column_name|value                |nb |
        +-----------+---------------------+---+
        |id         |3                    |1  |
        |my_array   |[{"a":1,"b":2,"c":3}]|1  |
        +-----------+---------------------+---+
        <BLANKLINE>
        1 rows were only found in 'right' :
        Most frequent values in 'right' for each column :
        +-----------+---------------------------+---+
        |column_name|value                      |nb |
        +-----------+---------------------------+---+
        |id         |4                          |1  |
        |my_array   |[{"a":1,"b":2,"c":3,"d":4}]|1  |
        +-----------+---------------------------+---+
        <BLANKLINE>

        >>> diff_result.export_to_html(output_file_path="test_working_dir/compare_dataframes_example_1.html")
        Report exported as test_working_dir/compare_dataframes_example_1.html

        [Check out the exported report here](../diff_reports/compare_dataframes_example_1.html)

    Examples: Example 2: diff on complex structures
        By adding `"my_array!.a"` to the join_cols argument, the array gets unnested for the diff
        >>> diff_result_unnested = compare_dataframes(df1, df2, join_cols=["id", "my_array!.a"])
        <BLANKLINE>
        Analyzing differences...
        Generating the diff by joining the DataFrames together using the provided column: id
        Generating the diff by joining the DataFrames together using the provided columns: ['id', 'my_array!.a']

        >>> diff_result_unnested.display()
        Schema has changed:
        @@ -1,4 +1,5 @@
        <BLANKLINE>
         id INT
         my_array!.a INT
         my_array!.b INT
         my_array!.c INT
        +my_array!.d INT
        WARNING: columns that do not match both sides will be ignored
        <BLANKLINE>
        diff NOT ok
        <BLANKLINE>
        WARNING: This diff has multiple granularity levels, we will print the results for each granularity level,
                 but we recommend to export the results to html for a much more digest result.
        <BLANKLINE>
        ##############################################################
        Granularity : root (4 rows)
        <BLANKLINE>
        Row count ok: 3 rows
        <BLANKLINE>
        2 (50.0%) rows are identical
        0 (0.0%) rows have changed
        1 (25.0%) rows are only in 'left'
        1 (25.0%) rows are only in 'right
        <BLANKLINE>
        1 rows were only found in 'left' :
        Most frequent values in 'left' for each column :
        +-----------+-----+---+
        |column_name|value|nb |
        +-----------+-----+---+
        |id         |3    |1  |
        |my_array!.a|1    |2  |
        |my_array!.b|2    |2  |
        |my_array!.c|3    |2  |
        +-----------+-----+---+
        <BLANKLINE>
        1 rows were only found in 'right' :
        Most frequent values in 'right' for each column :
        +-----------+-----+---+
        |column_name|value|nb |
        +-----------+-----+---+
        |id         |4    |1  |
        |my_array!.a|1    |1  |
        |my_array!.a|2    |1  |
        |my_array!.b|2    |2  |
        |my_array!.c|3    |2  |
        |my_array!.d|4    |3  |
        +-----------+-----+---+
        <BLANKLINE>
        ##############################################################
        Granularity : my_array! (5 rows)
        <BLANKLINE>
        Row count ok: 3 rows
        <BLANKLINE>
        1 (20.0%) rows are identical
        0 (0.0%) rows have changed
        2 (40.0%) rows are only in 'left'
        2 (40.0%) rows are only in 'right
        <BLANKLINE>
        2 rows were only found in 'left' :
        Most frequent values in 'left' for each column :
        +-----------+-----+---+
        |column_name|value|nb |
        +-----------+-----+---+
        |id         |3    |1  |
        |my_array!.a|1    |2  |
        |my_array!.b|2    |2  |
        |my_array!.c|3    |2  |
        +-----------+-----+---+
        <BLANKLINE>
        2 rows were only found in 'right' :
        Most frequent values in 'right' for each column :
        +-----------+-----+---+
        |column_name|value|nb |
        +-----------+-----+---+
        |id         |4    |1  |
        |my_array!.a|1    |1  |
        |my_array!.a|2    |1  |
        |my_array!.b|2    |2  |
        |my_array!.c|3    |2  |
        |my_array!.d|4    |3  |
        +-----------+-----+---+
        <BLANKLINE>

        >>> diff_result_unnested.export_to_html(output_file_path="test_working_dir/compare_dataframes_example_2.html")
        Report exported as test_working_dir/compare_dataframes_example_2.html

        [Check out the exported report here](../diff_reports/compare_dataframes_example_2.html)
    """
    print("\nAnalyzing differences...")

    if join_cols == []:
        join_cols = None
    specified_join_cols = join_cols
    left_df = convert_all_maps_to_arrays(left_df)
    right_df = convert_all_maps_to_arrays(right_df)

    if join_cols is None:
        left_flat = flatten(left_df, struct_separator=STRUCT_SEPARATOR_REPLACEMENT)
        right_flat = flatten(right_df, struct_separator=STRUCT_SEPARATOR_REPLACEMENT)
        join_cols, _ = _get_join_cols(
            left_flat,
            right_flat,
            join_cols,
        )
    else:
        validate_fields_exist(join_cols, nested.fields(left_df))
        validate_fields_exist(join_cols, nested.fields(right_df))

    global_schema_diff_result = diff_dataframe_schemas(left_df, right_df, join_cols)
    left_df, right_df = _harmonize_and_normalize_dataframes(
        left_df,
        right_df,
        skip_make_dataframes_comparable=global_schema_diff_result.same_schema,
    )

    diff_dataframe_shards = _build_diff_dataframe_shards(
        left_df,
        right_df,
        global_schema_diff_result,
        join_cols,
        specified_join_cols,
    )
    diff_result = DiffResult(
        global_schema_diff_result,
        diff_dataframe_shards,
        join_cols,
    )

    return diff_result

DiffResult

Object summarizing the results of a diff between two DataFrames.

Source code in spark_frame/data_diff/diff_result.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
339
340
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
class DiffResult:
    """Object summarizing the results of a diff between two DataFrames."""

    def __init__(
        self,
        schema_diff_result: SchemaDiffResult,
        diff_df_shards: Dict[str, DataFrame],
        join_cols: List[str],
    ) -> None:
        """Class containing the results of a diff between two DataFrames"""
        self.schema_diff_result: SchemaDiffResult = schema_diff_result
        self.diff_df_shards: Dict[str, DataFrame] = diff_df_shards
        """A dict containing one DataFrame for each level of granularity generated by the diff.

        The DataFrames have the following schema:

        - All fields from join_cols present at this level of granularity
        - For all other fields at this granularity level:
          a Column `col_name: STRUCT<left_value, right_value, is_equal>`
        - A Column `__EXISTS__: STRUCT<left_value, right_value>`
        - A Column `__IS_EQUAL__: BOOLEAN`

        In the simplest cases, there is only one granularity level, called the root level and represented
        by the string `""`. When comparing DataFrames containing arrays of structs, if the user passes a repeated
        field as join_cols (for example `"a!.id"`), then each level of granularity will be generated.
        In the example, there will be two: the root level `""` containing all root-level columns, and the
        level `"a!"` containing all the fields inside the exploded array `a!`; with one row per element inside `a!`.
        """
        self.join_cols: List[str] = join_cols
        """The list of column names to join"""

    @property
    def same_schema(self) -> bool:
        return self.schema_diff_result.same_schema

    @cached_property
    def same_data(self) -> bool:
        return self.top_per_col_state_df.where(
            f.col("state") != f.lit("no_change"),
        ).isEmpty()

    @cached_property
    def total_nb_rows(self) -> int:
        a_join_col = next(col for col in self.join_cols if REPETITION_MARKER not in col)
        return self.top_per_col_state_df.where(
            f.col("column_name") == f.lit(a_join_col),
        ).count()

    @property
    def is_ok(self) -> bool:
        return self.same_schema and self.same_data

    @cached_property
    def diff_stats_shards(self) -> Dict[str, DiffStats]:
        return self._compute_diff_stats_shards()

    @cached_property
    def top_per_col_state_df(self) -> DataFrame:
        def generate() -> Generator[DataFrame, None, None]:
            for key, diff_df in self.diff_df_shards.items():
                keep_cols = [
                    col_name for col_name in self.schema_diff_result.column_names if get_granularity(col_name) == key
                ]
                df = self._compute_top_per_col_state_df(diff_df)
                yield df.where(f.col("column_name").isin(keep_cols))

        return union_dataframes(*generate()).localCheckpoint()

    def get_diff_per_col_df(self, max_nb_rows_per_col_state: int) -> DataFrame:
        """Return a DataFrame that gives for each column and each column state (changed, no_change, only_in_left,
        only_in_right) the total number of occurences and the most frequent occurrences.

        The results returned by this method are cached to avoid unecessary recomputations.

        !!! warning
            The arrays contained in the field `diff` are NOT guaranteed to be sorted,
            and Spark currently does not provide any way to perform a sort_by on an ARRAY<STRUCT>.

        Args:
            max_nb_rows_per_col_state: The maximal size of the arrays in `diff`

        Returns:
            A DataFrame with the following schema:

                root
                 |-- column_number: integer (nullable = true)
                 |-- column_name: string (nullable = true)
                 |-- counts.total: long (nullable = false)
                 |-- counts.changed: long (nullable = false)
                 |-- counts.no_change: long (nullable = false)
                 |-- counts.only_in_left: long (nullable = false)
                 |-- counts.only_in_right: long (nullable = false)
                 |-- diff.changed!.left_value: string (nullable = true)
                 |-- diff.changed!.right_value: string (nullable = true)
                 |-- diff.changed!.nb: long (nullable = false)
                 |-- diff.no_change!.value: string (nullable = true)
                 |-- diff.no_change!.nb: long (nullable = false)
                 |-- diff.only_in_left!.value: string (nullable = true)
                 |-- diff.only_in_left!.nb: long (nullable = false)
                 |-- diff.only_in_right!.value: string (nullable = true)
                 |-- diff.only_in_right!.nb: long (nullable = false)
                <BLANKLINE>

        Examples:
            >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
            >>> diff_result = _get_test_diff_result()
            >>> diff_result.diff_df_shards[''].show(truncate=False)
            +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
            |id                           |c1                           |c2                           |c3                               |c4                               |__EXISTS__   |__IS_EQUAL__|__SAMPLE_ID__|
            +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
            |{1, 1, true, true, true}     |{a, a, true, true, true}     |{1, 1, true, true, true}     |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |true        |[{"id": 1}]  |
            |{2, 2, true, true, true}     |{b, b, true, true, true}     |{2, 3, false, true, true}    |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |false       |[{"id": 2}]  |
            |{3, 3, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 3}]  |
            |{4, 4, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 4}]  |
            |{5, NULL, false, true, false}|{c, NULL, false, true, false}|{3, NULL, false, true, false}|{3, NULL, false, true, false}    |{NULL, NULL, false, false, false}|{true, false}|false       |[{"id": 5}]  |
            |{NULL, 6, false, false, true}|{NULL, f, false, false, true}|{NULL, 3, false, false, true}|{NULL, NULL, false, false, false}|{NULL, 3, false, false, true}    |{false, true}|false       |[{"id": 6}]  |
            +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
            <BLANKLINE>
            >>> diff_result.top_per_col_state_df.show(100)
            +-----------+-------------+----------+-----------+---+-----------+-------+
            |column_name|        state|left_value|right_value| nb| sample_ids|row_num|
            +-----------+-------------+----------+-----------+---+-----------+-------+
            |         c1|    no_change|         b|          b|  3|[{"id": 2}]|      1|
            |         c1|    no_change|         a|          a|  1|[{"id": 1}]|      2|
            |         c1| only_in_left|         c|       NULL|  1|[{"id": 5}]|      1|
            |         c1|only_in_right|      NULL|          f|  1|[{"id": 6}]|      1|
            |         c2|      changed|         2|          4|  2|[{"id": 3}]|      1|
            |         c2|      changed|         2|          3|  1|[{"id": 2}]|      2|
            |         c2|    no_change|         1|          1|  1|[{"id": 1}]|      1|
            |         c2| only_in_left|         3|       NULL|  1|[{"id": 5}]|      1|
            |         c2|only_in_right|      NULL|          3|  1|[{"id": 6}]|      1|
            |         c3| only_in_left|         1|       NULL|  2|[{"id": 1}]|      1|
            |         c3| only_in_left|         2|       NULL|  2|[{"id": 3}]|      2|
            |         c3| only_in_left|         3|       NULL|  1|[{"id": 5}]|      3|
            |         c4|only_in_right|      NULL|          1|  2|[{"id": 1}]|      1|
            |         c4|only_in_right|      NULL|          2|  2|[{"id": 3}]|      2|
            |         c4|only_in_right|      NULL|          3|  1|[{"id": 6}]|      3|
            |         id|    no_change|         1|          1|  1|[{"id": 1}]|      1|
            |         id|    no_change|         2|          2|  1|[{"id": 2}]|      2|
            |         id|    no_change|         3|          3|  1|[{"id": 3}]|      3|
            |         id|    no_change|         4|          4|  1|[{"id": 4}]|      4|
            |         id| only_in_left|         5|       NULL|  1|[{"id": 5}]|      1|
            |         id|only_in_right|      NULL|          6|  1|[{"id": 6}]|      1|
            +-----------+-------------+----------+-----------+---+-----------+-------+
            <BLANKLINE>

            >>> diff_per_col_df = diff_result.get_diff_per_col_df(max_nb_rows_per_col_state=10)
            >>> from spark_frame import nested
            >>> nested.print_schema(diff_per_col_df)
            root
             |-- column_number: integer (nullable = true)
             |-- column_name: string (nullable = true)
             |-- counts.total: long (nullable = false)
             |-- counts.changed: long (nullable = false)
             |-- counts.no_change: long (nullable = false)
             |-- counts.only_in_left: long (nullable = false)
             |-- counts.only_in_right: long (nullable = false)
             |-- diff.changed!.left_value: string (nullable = true)
             |-- diff.changed!.right_value: string (nullable = true)
             |-- diff.changed!.nb: long (nullable = false)
             |-- diff.changed!.sample_ids!: string (nullable = true)
             |-- diff.no_change!.value: string (nullable = true)
             |-- diff.no_change!.nb: long (nullable = false)
             |-- diff.no_change!.sample_ids!: string (nullable = true)
             |-- diff.only_in_left!.value: string (nullable = true)
             |-- diff.only_in_left!.nb: long (nullable = false)
             |-- diff.only_in_left!.sample_ids!: string (nullable = true)
             |-- diff.only_in_right!.value: string (nullable = true)
             |-- diff.only_in_right!.nb: long (nullable = false)
             |-- diff.only_in_right!.sample_ids!: string (nullable = true)
            <BLANKLINE>
            >>> diff_per_col_df.show(truncate=False)
            +-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
            |column_number|column_name|counts         |diff                                                                                                                                    |
            +-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
            |0            |id         |{6, 0, 4, 1, 1}|{[], [{1, 1, [{"id": 1}]}, {2, 1, [{"id": 2}]}, {3, 1, [{"id": 3}]}, {4, 1, [{"id": 4}]}], [{5, 1, [{"id": 5}]}], [{6, 1, [{"id": 6}]}]}|
            |1            |c1         |{6, 0, 4, 1, 1}|{[], [{b, 3, [{"id": 2}]}, {a, 1, [{"id": 1}]}], [{c, 1, [{"id": 5}]}], [{f, 1, [{"id": 6}]}]}                                          |
            |2            |c2         |{6, 3, 1, 1, 1}|{[{2, 4, 2, [{"id": 3}]}, {2, 3, 1, [{"id": 2}]}], [{1, 1, [{"id": 1}]}], [{3, 1, [{"id": 5}]}], [{3, 1, [{"id": 6}]}]}                 |
            |3            |c3         |{5, 0, 0, 5, 0}|{[], [], [{1, 2, [{"id": 1}]}, {2, 2, [{"id": 3}]}, {3, 1, [{"id": 5}]}], []}                                                           |
            |4            |c4         |{5, 0, 0, 0, 5}|{[], [], [], [{1, 2, [{"id": 1}]}, {2, 2, [{"id": 3}]}, {3, 1, [{"id": 6}]}]}                                                           |
            +-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
            <BLANKLINE>
        """  # noqa: E501
        return _get_diff_per_col_df_with_cache(self, max_nb_rows_per_col_state)

    def get_sample_df_shards(self, max_nb_rows_per_col_state: int) -> List[DataFrame]:
        return _get_sample_df_shards_with_cache(self, max_nb_rows_per_col_state)

    def _compute_diff_stats_shard(self, diff_df_shard: DataFrame) -> DiffStats:
        """Given a diff_df and its list of join_cols, return stats about the number of differing or missing rows

        >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
        >>> diff_result = _get_test_diff_result()
        >>> diff_result.diff_df_shards[''].select('__EXISTS__', '__IS_EQUAL__').show()
        +-------------+------------+
        |   __EXISTS__|__IS_EQUAL__|
        +-------------+------------+
        | {true, true}|        true|
        | {true, true}|       false|
        | {true, true}|       false|
        | {true, true}|       false|
        |{true, false}|       false|
        |{false, true}|       false|
        +-------------+------------+
        <BLANKLINE>
        >>> diff_result._compute_diff_stats_shards()['']
        DiffStats(total=6, no_change=1, changed=3, in_left=5, in_right=5, only_in_left=1, only_in_right=1)
        """
        res_df = diff_df_shard.select(
            f.count(f.lit(1)).alias("total"),
            f.sum(
                f.when(
                    PREDICATES.present_in_both & PREDICATES.row_is_equal,
                    f.lit(1),
                ).otherwise(f.lit(0)),
            ).alias(
                "no_change",
            ),
            f.sum(
                f.when(
                    PREDICATES.present_in_both & PREDICATES.row_changed,
                    f.lit(1),
                ).otherwise(f.lit(0)),
            ).alias(
                "changed",
            ),
            f.sum(f.when(PREDICATES.in_left, f.lit(1)).otherwise(f.lit(0))).alias(
                "in_left",
            ),
            f.sum(f.when(PREDICATES.in_right, f.lit(1)).otherwise(f.lit(0))).alias(
                "in_right",
            ),
            f.sum(f.when(PREDICATES.only_in_left, f.lit(1)).otherwise(f.lit(0))).alias(
                "only_in_left",
            ),
            f.sum(f.when(PREDICATES.only_in_right, f.lit(1)).otherwise(f.lit(0))).alias(
                "only_in_right",
            ),
        )
        res = res_df.collect()
        return DiffStats(
            **{k: (v if v is not None else 0) for k, v in res[0].asDict().items()},
        )

    def _compute_diff_stats_shards(self) -> Dict[str, DiffStats]:
        """Given a diff_df and its list of join_cols, return stats about the number of differing or missing rows

        >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
        >>> diff_result = _get_test_diff_result()
        >>> diff_result.diff_df_shards[''].select('__EXISTS__', '__IS_EQUAL__').show()
        +-------------+------------+
        |   __EXISTS__|__IS_EQUAL__|
        +-------------+------------+
        | {true, true}|        true|
        | {true, true}|       false|
        | {true, true}|       false|
        | {true, true}|       false|
        |{true, false}|       false|
        |{false, true}|       false|
        +-------------+------------+
        <BLANKLINE>
        >>> diff_result._compute_diff_stats_shards()['']
        DiffStats(total=6, no_change=1, changed=3, in_left=5, in_right=5, only_in_left=1, only_in_right=1)
        """
        return {
            key: self._compute_diff_stats_shard(diff_df_shard) for key, diff_df_shard in self.diff_df_shards.items()
        }

    def _compute_top_per_col_state_df(self, diff_df: DataFrame) -> DataFrame:
        """Given a diff_df, return a DataFrame with the following properties:

        - One row per tuple (column_name, state, left_value, right_value)
          (where `state` can take the following values: "only_in_left", "only_in_right", "no_change", "changed")
        - A column `nb` that gives the number of occurrence of this specific tuple
        - At most `max_nb_rows_per_col_state` per tuple (column_name, state). Rows with the highest "nb" are kept first.

        Examples:
            >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
            >>> _diff_result = _get_test_diff_result()
            >>> diff_df = _diff_result.diff_df_shards['']
            >>> diff_df.show(truncate=False)
            +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
            |id                           |c1                           |c2                           |c3                               |c4                               |__EXISTS__   |__IS_EQUAL__|__SAMPLE_ID__|
            +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
            |{1, 1, true, true, true}     |{a, a, true, true, true}     |{1, 1, true, true, true}     |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |true        |[{"id": 1}]  |
            |{2, 2, true, true, true}     |{b, b, true, true, true}     |{2, 3, false, true, true}    |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |false       |[{"id": 2}]  |
            |{3, 3, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 3}]  |
            |{4, 4, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 4}]  |
            |{5, NULL, false, true, false}|{c, NULL, false, true, false}|{3, NULL, false, true, false}|{3, NULL, false, true, false}    |{NULL, NULL, false, false, false}|{true, false}|false       |[{"id": 5}]  |
            |{NULL, 6, false, false, true}|{NULL, f, false, false, true}|{NULL, 3, false, false, true}|{NULL, NULL, false, false, false}|{NULL, 3, false, false, true}    |{false, true}|false       |[{"id": 6}]  |
            +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
            <BLANKLINE>
            >>> (_diff_result._compute_top_per_col_state_df(diff_df)
            ...  .orderBy("column_name", "state", "left_value", "right_value")
            ... ).show(100)
            +-----------+-------------+----------+-----------+---+-----------+-------+
            |column_name|        state|left_value|right_value| nb| sample_ids|row_num|
            +-----------+-------------+----------+-----------+---+-----------+-------+
            |         c1|    no_change|         a|          a|  1|[{"id": 1}]|      2|
            |         c1|    no_change|         b|          b|  3|[{"id": 2}]|      1|
            |         c1| only_in_left|         c|       NULL|  1|[{"id": 5}]|      1|
            |         c1|only_in_right|      NULL|          f|  1|[{"id": 6}]|      1|
            |         c2|      changed|         2|          3|  1|[{"id": 2}]|      2|
            |         c2|      changed|         2|          4|  2|[{"id": 3}]|      1|
            |         c2|    no_change|         1|          1|  1|[{"id": 1}]|      1|
            |         c2| only_in_left|         3|       NULL|  1|[{"id": 5}]|      1|
            |         c2|only_in_right|      NULL|          3|  1|[{"id": 6}]|      1|
            |         c3| only_in_left|         1|       NULL|  2|[{"id": 1}]|      1|
            |         c3| only_in_left|         2|       NULL|  2|[{"id": 3}]|      2|
            |         c3| only_in_left|         3|       NULL|  1|[{"id": 5}]|      3|
            |         c4|only_in_right|      NULL|          1|  2|[{"id": 1}]|      1|
            |         c4|only_in_right|      NULL|          2|  2|[{"id": 3}]|      2|
            |         c4|only_in_right|      NULL|          3|  1|[{"id": 6}]|      3|
            |         id|    no_change|         1|          1|  1|[{"id": 1}]|      1|
            |         id|    no_change|         2|          2|  1|[{"id": 2}]|      2|
            |         id|    no_change|         3|          3|  1|[{"id": 3}]|      3|
            |         id|    no_change|         4|          4|  1|[{"id": 4}]|      4|
            |         id| only_in_left|         5|       NULL|  1|[{"id": 5}]|      1|
            |         id|only_in_right|      NULL|          6|  1|[{"id": 6}]|      1|
            +-----------+-------------+----------+-----------+---+-----------+-------+
            <BLANKLINE>
        """  # noqa: E501
        diff_df = diff_df.drop(IS_EQUAL_COL_NAME, EXISTS_COL_NAME)
        unpivoted_diff_df = _unpivot(diff_df)

        only_in_left = f.col("diff")["exists_left"] & ~f.col("diff")["exists_right"]
        only_in_right = ~f.col("diff")["exists_left"] & f.col("diff")["exists_right"]
        exists_in_left_or_right = f.col("diff")["exists_left"] | f.col("diff")["exists_right"]

        df_1 = unpivoted_diff_df.select(
            "column_name",
            f.when(only_in_left, f.lit("only_in_left"))
            .when(only_in_right, f.lit("only_in_right"))
            .when(f.col("diff")["is_equal"], f.lit("no_change"))
            .otherwise(f.lit("changed"))
            .alias("state"),
            "diff.left_value",
            "diff.right_value",
            "diff.sample_ids",
        ).where(exists_in_left_or_right)
        window = Window.partitionBy("column_name", "state").orderBy(
            f.col("nb").desc(),
            f.col("left_value"),
            f.col("right_value"),
        )
        df_2 = (
            df_1.groupBy("column_name", "state", "left_value", "right_value")
            .agg(f.count(f.lit(1)).alias("nb"), f.first("sample_ids").alias("sample_ids"))
            .withColumn("row_num", f.row_number().over(window))
        )
        return df_2

    def display(
        self,
        show_examples: bool = False,
        diff_format_options: Optional[DiffFormatOptions] = None,
    ) -> None:
        """Print a summary of the results in the standard output

        Args:
            show_examples: If true, display example of rows for each type of change
            diff_format_options: Formatting options

        Examples:
            See [spark_frame.data_diff.compare_dataframes][spark_frame.data_diff.compare_dataframes] for more examples.

            >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
            >>> diff_result = _get_test_diff_result()
            >>> diff_result.display()
            Schema has changed:
            @@ -1,6 +1,6 @@
                 id INT
                 c1 STRING
                 c2 STRING
            -    c3 STRING
            +    c4 STRING
            <BLANKLINE>
            WARNING: columns that do not match both sides will be ignored
            <BLANKLINE>
            diff NOT ok
            <BLANKLINE>
            Row count ok: 5 rows
            <BLANKLINE>
            1 (16.67%) rows are identical
            3 (50.0%) rows have changed
            1 (16.67%) rows are only in 'left'
            1 (16.67%) rows are only in 'right
            <BLANKLINE>
            Found the following changes:
            +-----------+-------------+----------+-----------+--------------+
            |column_name|total_nb_diff|left_value|right_value|nb_differences|
            +-----------+-------------+----------+-----------+--------------+
            |c2         |3            |2         |4          |2             |
            |c2         |3            |2         |3          |1             |
            +-----------+-------------+----------+-----------+--------------+
            <BLANKLINE>
            1 rows were only found in 'left' :
            Most frequent values in 'left' for each column :
            +-----------+-----+---+
            |column_name|value|nb |
            +-----------+-----+---+
            |id         |5    |1  |
            |c1         |c    |1  |
            |c2         |3    |1  |
            |c3         |1    |2  |
            |c3         |2    |2  |
            |c3         |3    |1  |
            +-----------+-----+---+
            <BLANKLINE>
            1 rows were only found in 'right' :
            Most frequent values in 'right' for each column :
            +-----------+-----+---+
            |column_name|value|nb |
            +-----------+-----+---+
            |id         |6    |1  |
            |c1         |f    |1  |
            |c2         |3    |1  |
            |c4         |1    |2  |
            |c4         |2    |2  |
            |c4         |3    |1  |
            +-----------+-----+---+
            <BLANKLINE>
        """
        if diff_format_options is None:
            diff_format_options = DiffFormatOptions()
        from spark_frame.data_diff.diff_result_analyzer import DiffResultAnalyzer

        self.schema_diff_result.display()
        analyzer = DiffResultAnalyzer(diff_format_options)
        analyzer.display_diff_results(self, show_examples)

    def export_to_html(
        self,
        title: Optional[str] = None,
        output_file_path: str = "diff_report.html",
        encoding: str = "utf8",
        diff_format_options: Optional[DiffFormatOptions] = None,
    ) -> None:
        """Generate an HTML report of this diff result.

        This generates an HTML report file at the specified `output_file_path` URI location.

        The report file can be opened directly with a web browser, even without any internet connection.

        !!! info
            This method uses Spark's FileSystem API to write the report.
            This means that `output_file_path` behaves the same way as the path argument in `df.write.save(path)`:

            - It can be a fully qualified URI pointing to a location on a remote filesystem
              (e.g. "hdfs://...", "s3://...", etc.), provided that Spark is configured to access it
            - If a relative path with no scheme is specified (e.g. `output_file_path="diff_report.html"`), it will
              write on Spark's default's output location. For example:
                - when running locally, it will be the process current working directory.
                - when running on Hadoop, it will be the user's home directory on HDFS.
                - when running on the cloud (EMR, Dataproc, Azure Synapse, Databricks), it should write on the
                  default remote storage linked to the cluster.

        Args:
            title: The title of the report
            encoding: Encoding used when writing the html report
            output_file_path: URI of the file to write to.
            diff_format_options: Formatting options

        Examples:
            >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
            >>> diff_result = _get_test_diff_result()
            >>> diff_result.export_to_html(output_file_path="test_working_dir/diff_result_export_to_html_example.html")
            Report exported as test_working_dir/diff_result_export_to_html_example.html

            [Check out the exported report here](../diff_reports/diff_result_export_to_html_example.html)
        """
        if diff_format_options is None:
            diff_format_options = DiffFormatOptions()
        from spark_frame.data_diff.diff_result_analyzer import DiffResultAnalyzer

        analyzer = DiffResultAnalyzer(diff_format_options)
        diff_result_summary = analyzer.get_diff_result_summary(self)
        export_html_diff_report(
            diff_result_summary,
            title=title,
            output_file_path=output_file_path,
            encoding=encoding,
        )

diff_df_shards: Dict[str, DataFrame] = diff_df_shards instance-attribute

A dict containing one DataFrame for each level of granularity generated by the diff.

The DataFrames have the following schema:

  • All fields from join_cols present at this level of granularity
  • For all other fields at this granularity level: a Column col_name: STRUCT<left_value, right_value, is_equal>
  • A Column __EXISTS__: STRUCT<left_value, right_value>
  • A Column __IS_EQUAL__: BOOLEAN

In the simplest cases, there is only one granularity level, called the root level and represented by the string "". When comparing DataFrames containing arrays of structs, if the user passes a repeated field as join_cols (for example "a!.id"), then each level of granularity will be generated. In the example, there will be two: the root level "" containing all root-level columns, and the level "a!" containing all the fields inside the exploded array a!; with one row per element inside a!.

display(show_examples: bool = False, diff_format_options: Optional[DiffFormatOptions] = None) -> None

Print a summary of the results in the standard output

Parameters:

Name Type Description Default
show_examples bool

If true, display example of rows for each type of change

False
diff_format_options Optional[DiffFormatOptions]

Formatting options

None

Examples:

See spark_frame.data_diff.compare_dataframes for more examples.

>>> from spark_frame.data_diff.diff_result import _get_test_diff_result
>>> diff_result = _get_test_diff_result()
>>> diff_result.display()
Schema has changed:
@@ -1,6 +1,6 @@
     id INT
     c1 STRING
     c2 STRING
-    c3 STRING
+    c4 STRING

WARNING: columns that do not match both sides will be ignored

diff NOT ok

Row count ok: 5 rows

1 (16.67%) rows are identical
3 (50.0%) rows have changed
1 (16.67%) rows are only in 'left'
1 (16.67%) rows are only in 'right

Found the following changes:
+-----------+-------------+----------+-----------+--------------+
|column_name|total_nb_diff|left_value|right_value|nb_differences|
+-----------+-------------+----------+-----------+--------------+
|c2         |3            |2         |4          |2             |
|c2         |3            |2         |3          |1             |
+-----------+-------------+----------+-----------+--------------+

1 rows were only found in 'left' :
Most frequent values in 'left' for each column :
+-----------+-----+---+
|column_name|value|nb |
+-----------+-----+---+
|id         |5    |1  |
|c1         |c    |1  |
|c2         |3    |1  |
|c3         |1    |2  |
|c3         |2    |2  |
|c3         |3    |1  |
+-----------+-----+---+

1 rows were only found in 'right' :
Most frequent values in 'right' for each column :
+-----------+-----+---+
|column_name|value|nb |
+-----------+-----+---+
|id         |6    |1  |
|c1         |f    |1  |
|c2         |3    |1  |
|c4         |1    |2  |
|c4         |2    |2  |
|c4         |3    |1  |
+-----------+-----+---+
Source code in spark_frame/data_diff/diff_result.py
def display(
    self,
    show_examples: bool = False,
    diff_format_options: Optional[DiffFormatOptions] = None,
) -> None:
    """Print a summary of the results in the standard output

    Args:
        show_examples: If true, display example of rows for each type of change
        diff_format_options: Formatting options

    Examples:
        See [spark_frame.data_diff.compare_dataframes][spark_frame.data_diff.compare_dataframes] for more examples.

        >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
        >>> diff_result = _get_test_diff_result()
        >>> diff_result.display()
        Schema has changed:
        @@ -1,6 +1,6 @@
             id INT
             c1 STRING
             c2 STRING
        -    c3 STRING
        +    c4 STRING
        <BLANKLINE>
        WARNING: columns that do not match both sides will be ignored
        <BLANKLINE>
        diff NOT ok
        <BLANKLINE>
        Row count ok: 5 rows
        <BLANKLINE>
        1 (16.67%) rows are identical
        3 (50.0%) rows have changed
        1 (16.67%) rows are only in 'left'
        1 (16.67%) rows are only in 'right
        <BLANKLINE>
        Found the following changes:
        +-----------+-------------+----------+-----------+--------------+
        |column_name|total_nb_diff|left_value|right_value|nb_differences|
        +-----------+-------------+----------+-----------+--------------+
        |c2         |3            |2         |4          |2             |
        |c2         |3            |2         |3          |1             |
        +-----------+-------------+----------+-----------+--------------+
        <BLANKLINE>
        1 rows were only found in 'left' :
        Most frequent values in 'left' for each column :
        +-----------+-----+---+
        |column_name|value|nb |
        +-----------+-----+---+
        |id         |5    |1  |
        |c1         |c    |1  |
        |c2         |3    |1  |
        |c3         |1    |2  |
        |c3         |2    |2  |
        |c3         |3    |1  |
        +-----------+-----+---+
        <BLANKLINE>
        1 rows were only found in 'right' :
        Most frequent values in 'right' for each column :
        +-----------+-----+---+
        |column_name|value|nb |
        +-----------+-----+---+
        |id         |6    |1  |
        |c1         |f    |1  |
        |c2         |3    |1  |
        |c4         |1    |2  |
        |c4         |2    |2  |
        |c4         |3    |1  |
        +-----------+-----+---+
        <BLANKLINE>
    """
    if diff_format_options is None:
        diff_format_options = DiffFormatOptions()
    from spark_frame.data_diff.diff_result_analyzer import DiffResultAnalyzer

    self.schema_diff_result.display()
    analyzer = DiffResultAnalyzer(diff_format_options)
    analyzer.display_diff_results(self, show_examples)

export_to_html(title: Optional[str] = None, output_file_path: str = 'diff_report.html', encoding: str = 'utf8', diff_format_options: Optional[DiffFormatOptions] = None) -> None

Generate an HTML report of this diff result.

This generates an HTML report file at the specified output_file_path URI location.

The report file can be opened directly with a web browser, even without any internet connection.

Info

This method uses Spark's FileSystem API to write the report. This means that output_file_path behaves the same way as the path argument in df.write.save(path):

  • It can be a fully qualified URI pointing to a location on a remote filesystem (e.g. "hdfs://...", "s3://...", etc.), provided that Spark is configured to access it
  • If a relative path with no scheme is specified (e.g. output_file_path="diff_report.html"), it will write on Spark's default's output location. For example:
    • when running locally, it will be the process current working directory.
    • when running on Hadoop, it will be the user's home directory on HDFS.
    • when running on the cloud (EMR, Dataproc, Azure Synapse, Databricks), it should write on the default remote storage linked to the cluster.

Parameters:

Name Type Description Default
title Optional[str]

The title of the report

None
encoding str

Encoding used when writing the html report

'utf8'
output_file_path str

URI of the file to write to.

'diff_report.html'
diff_format_options Optional[DiffFormatOptions]

Formatting options

None

Examples:

>>> from spark_frame.data_diff.diff_result import _get_test_diff_result
>>> diff_result = _get_test_diff_result()
>>> diff_result.export_to_html(output_file_path="test_working_dir/diff_result_export_to_html_example.html")
Report exported as test_working_dir/diff_result_export_to_html_example.html

Check out the exported report here

Source code in spark_frame/data_diff/diff_result.py
def export_to_html(
    self,
    title: Optional[str] = None,
    output_file_path: str = "diff_report.html",
    encoding: str = "utf8",
    diff_format_options: Optional[DiffFormatOptions] = None,
) -> None:
    """Generate an HTML report of this diff result.

    This generates an HTML report file at the specified `output_file_path` URI location.

    The report file can be opened directly with a web browser, even without any internet connection.

    !!! info
        This method uses Spark's FileSystem API to write the report.
        This means that `output_file_path` behaves the same way as the path argument in `df.write.save(path)`:

        - It can be a fully qualified URI pointing to a location on a remote filesystem
          (e.g. "hdfs://...", "s3://...", etc.), provided that Spark is configured to access it
        - If a relative path with no scheme is specified (e.g. `output_file_path="diff_report.html"`), it will
          write on Spark's default's output location. For example:
            - when running locally, it will be the process current working directory.
            - when running on Hadoop, it will be the user's home directory on HDFS.
            - when running on the cloud (EMR, Dataproc, Azure Synapse, Databricks), it should write on the
              default remote storage linked to the cluster.

    Args:
        title: The title of the report
        encoding: Encoding used when writing the html report
        output_file_path: URI of the file to write to.
        diff_format_options: Formatting options

    Examples:
        >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
        >>> diff_result = _get_test_diff_result()
        >>> diff_result.export_to_html(output_file_path="test_working_dir/diff_result_export_to_html_example.html")
        Report exported as test_working_dir/diff_result_export_to_html_example.html

        [Check out the exported report here](../diff_reports/diff_result_export_to_html_example.html)
    """
    if diff_format_options is None:
        diff_format_options = DiffFormatOptions()
    from spark_frame.data_diff.diff_result_analyzer import DiffResultAnalyzer

    analyzer = DiffResultAnalyzer(diff_format_options)
    diff_result_summary = analyzer.get_diff_result_summary(self)
    export_html_diff_report(
        diff_result_summary,
        title=title,
        output_file_path=output_file_path,
        encoding=encoding,
    )

get_diff_per_col_df(max_nb_rows_per_col_state: int) -> DataFrame

Return a DataFrame that gives for each column and each column state (changed, no_change, only_in_left, only_in_right) the total number of occurences and the most frequent occurrences.

The results returned by this method are cached to avoid unecessary recomputations.

Warning

The arrays contained in the field diff are NOT guaranteed to be sorted, and Spark currently does not provide any way to perform a sort_by on an ARRAY.

Parameters:

Name Type Description Default
max_nb_rows_per_col_state int

The maximal size of the arrays in diff

required

Returns:

Type Description
DataFrame

A DataFrame with the following schema:

root |-- column_number: integer (nullable = true) |-- column_name: string (nullable = true) |-- counts.total: long (nullable = false) |-- counts.changed: long (nullable = false) |-- counts.no_change: long (nullable = false) |-- counts.only_in_left: long (nullable = false) |-- counts.only_in_right: long (nullable = false) |-- diff.changed!.left_value: string (nullable = true) |-- diff.changed!.right_value: string (nullable = true) |-- diff.changed!.nb: long (nullable = false) |-- diff.no_change!.value: string (nullable = true) |-- diff.no_change!.nb: long (nullable = false) |-- diff.only_in_left!.value: string (nullable = true) |-- diff.only_in_left!.nb: long (nullable = false) |-- diff.only_in_right!.value: string (nullable = true) |-- diff.only_in_right!.nb: long (nullable = false)

Examples:

>>> from spark_frame.data_diff.diff_result import _get_test_diff_result
>>> diff_result = _get_test_diff_result()
>>> diff_result.diff_df_shards[''].show(truncate=False)
+-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
|id                           |c1                           |c2                           |c3                               |c4                               |__EXISTS__   |__IS_EQUAL__|__SAMPLE_ID__|
+-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
|{1, 1, true, true, true}     |{a, a, true, true, true}     |{1, 1, true, true, true}     |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |true        |[{"id": 1}]  |
|{2, 2, true, true, true}     |{b, b, true, true, true}     |{2, 3, false, true, true}    |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |false       |[{"id": 2}]  |
|{3, 3, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 3}]  |
|{4, 4, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 4}]  |
|{5, NULL, false, true, false}|{c, NULL, false, true, false}|{3, NULL, false, true, false}|{3, NULL, false, true, false}    |{NULL, NULL, false, false, false}|{true, false}|false       |[{"id": 5}]  |
|{NULL, 6, false, false, true}|{NULL, f, false, false, true}|{NULL, 3, false, false, true}|{NULL, NULL, false, false, false}|{NULL, 3, false, false, true}    |{false, true}|false       |[{"id": 6}]  |
+-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+

>>> diff_result.top_per_col_state_df.show(100)
+-----------+-------------+----------+-----------+---+-----------+-------+
|column_name|        state|left_value|right_value| nb| sample_ids|row_num|
+-----------+-------------+----------+-----------+---+-----------+-------+
|         c1|    no_change|         b|          b|  3|[{"id": 2}]|      1|
|         c1|    no_change|         a|          a|  1|[{"id": 1}]|      2|
|         c1| only_in_left|         c|       NULL|  1|[{"id": 5}]|      1|
|         c1|only_in_right|      NULL|          f|  1|[{"id": 6}]|      1|
|         c2|      changed|         2|          4|  2|[{"id": 3}]|      1|
|         c2|      changed|         2|          3|  1|[{"id": 2}]|      2|
|         c2|    no_change|         1|          1|  1|[{"id": 1}]|      1|
|         c2| only_in_left|         3|       NULL|  1|[{"id": 5}]|      1|
|         c2|only_in_right|      NULL|          3|  1|[{"id": 6}]|      1|
|         c3| only_in_left|         1|       NULL|  2|[{"id": 1}]|      1|
|         c3| only_in_left|         2|       NULL|  2|[{"id": 3}]|      2|
|         c3| only_in_left|         3|       NULL|  1|[{"id": 5}]|      3|
|         c4|only_in_right|      NULL|          1|  2|[{"id": 1}]|      1|
|         c4|only_in_right|      NULL|          2|  2|[{"id": 3}]|      2|
|         c4|only_in_right|      NULL|          3|  1|[{"id": 6}]|      3|
|         id|    no_change|         1|          1|  1|[{"id": 1}]|      1|
|         id|    no_change|         2|          2|  1|[{"id": 2}]|      2|
|         id|    no_change|         3|          3|  1|[{"id": 3}]|      3|
|         id|    no_change|         4|          4|  1|[{"id": 4}]|      4|
|         id| only_in_left|         5|       NULL|  1|[{"id": 5}]|      1|
|         id|only_in_right|      NULL|          6|  1|[{"id": 6}]|      1|
+-----------+-------------+----------+-----------+---+-----------+-------+
>>> diff_per_col_df = diff_result.get_diff_per_col_df(max_nb_rows_per_col_state=10)
>>> from spark_frame import nested
>>> nested.print_schema(diff_per_col_df)
root
 |-- column_number: integer (nullable = true)
 |-- column_name: string (nullable = true)
 |-- counts.total: long (nullable = false)
 |-- counts.changed: long (nullable = false)
 |-- counts.no_change: long (nullable = false)
 |-- counts.only_in_left: long (nullable = false)
 |-- counts.only_in_right: long (nullable = false)
 |-- diff.changed!.left_value: string (nullable = true)
 |-- diff.changed!.right_value: string (nullable = true)
 |-- diff.changed!.nb: long (nullable = false)
 |-- diff.changed!.sample_ids!: string (nullable = true)
 |-- diff.no_change!.value: string (nullable = true)
 |-- diff.no_change!.nb: long (nullable = false)
 |-- diff.no_change!.sample_ids!: string (nullable = true)
 |-- diff.only_in_left!.value: string (nullable = true)
 |-- diff.only_in_left!.nb: long (nullable = false)
 |-- diff.only_in_left!.sample_ids!: string (nullable = true)
 |-- diff.only_in_right!.value: string (nullable = true)
 |-- diff.only_in_right!.nb: long (nullable = false)
 |-- diff.only_in_right!.sample_ids!: string (nullable = true)

>>> diff_per_col_df.show(truncate=False)
+-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
|column_number|column_name|counts         |diff                                                                                                                                    |
+-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
|0            |id         |{6, 0, 4, 1, 1}|{[], [{1, 1, [{"id": 1}]}, {2, 1, [{"id": 2}]}, {3, 1, [{"id": 3}]}, {4, 1, [{"id": 4}]}], [{5, 1, [{"id": 5}]}], [{6, 1, [{"id": 6}]}]}|
|1            |c1         |{6, 0, 4, 1, 1}|{[], [{b, 3, [{"id": 2}]}, {a, 1, [{"id": 1}]}], [{c, 1, [{"id": 5}]}], [{f, 1, [{"id": 6}]}]}                                          |
|2            |c2         |{6, 3, 1, 1, 1}|{[{2, 4, 2, [{"id": 3}]}, {2, 3, 1, [{"id": 2}]}], [{1, 1, [{"id": 1}]}], [{3, 1, [{"id": 5}]}], [{3, 1, [{"id": 6}]}]}                 |
|3            |c3         |{5, 0, 0, 5, 0}|{[], [], [{1, 2, [{"id": 1}]}, {2, 2, [{"id": 3}]}, {3, 1, [{"id": 5}]}], []}                                                           |
|4            |c4         |{5, 0, 0, 0, 5}|{[], [], [], [{1, 2, [{"id": 1}]}, {2, 2, [{"id": 3}]}, {3, 1, [{"id": 6}]}]}                                                           |
+-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
Source code in spark_frame/data_diff/diff_result.py
def get_diff_per_col_df(self, max_nb_rows_per_col_state: int) -> DataFrame:
    """Return a DataFrame that gives for each column and each column state (changed, no_change, only_in_left,
    only_in_right) the total number of occurences and the most frequent occurrences.

    The results returned by this method are cached to avoid unecessary recomputations.

    !!! warning
        The arrays contained in the field `diff` are NOT guaranteed to be sorted,
        and Spark currently does not provide any way to perform a sort_by on an ARRAY<STRUCT>.

    Args:
        max_nb_rows_per_col_state: The maximal size of the arrays in `diff`

    Returns:
        A DataFrame with the following schema:

            root
             |-- column_number: integer (nullable = true)
             |-- column_name: string (nullable = true)
             |-- counts.total: long (nullable = false)
             |-- counts.changed: long (nullable = false)
             |-- counts.no_change: long (nullable = false)
             |-- counts.only_in_left: long (nullable = false)
             |-- counts.only_in_right: long (nullable = false)
             |-- diff.changed!.left_value: string (nullable = true)
             |-- diff.changed!.right_value: string (nullable = true)
             |-- diff.changed!.nb: long (nullable = false)
             |-- diff.no_change!.value: string (nullable = true)
             |-- diff.no_change!.nb: long (nullable = false)
             |-- diff.only_in_left!.value: string (nullable = true)
             |-- diff.only_in_left!.nb: long (nullable = false)
             |-- diff.only_in_right!.value: string (nullable = true)
             |-- diff.only_in_right!.nb: long (nullable = false)
            <BLANKLINE>

    Examples:
        >>> from spark_frame.data_diff.diff_result import _get_test_diff_result
        >>> diff_result = _get_test_diff_result()
        >>> diff_result.diff_df_shards[''].show(truncate=False)
        +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
        |id                           |c1                           |c2                           |c3                               |c4                               |__EXISTS__   |__IS_EQUAL__|__SAMPLE_ID__|
        +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
        |{1, 1, true, true, true}     |{a, a, true, true, true}     |{1, 1, true, true, true}     |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |true        |[{"id": 1}]  |
        |{2, 2, true, true, true}     |{b, b, true, true, true}     |{2, 3, false, true, true}    |{1, NULL, false, true, false}    |{NULL, 1, false, false, true}    |{true, true} |false       |[{"id": 2}]  |
        |{3, 3, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 3}]  |
        |{4, 4, true, true, true}     |{b, b, true, true, true}     |{2, 4, false, true, true}    |{2, NULL, false, true, false}    |{NULL, 2, false, false, true}    |{true, true} |false       |[{"id": 4}]  |
        |{5, NULL, false, true, false}|{c, NULL, false, true, false}|{3, NULL, false, true, false}|{3, NULL, false, true, false}    |{NULL, NULL, false, false, false}|{true, false}|false       |[{"id": 5}]  |
        |{NULL, 6, false, false, true}|{NULL, f, false, false, true}|{NULL, 3, false, false, true}|{NULL, NULL, false, false, false}|{NULL, 3, false, false, true}    |{false, true}|false       |[{"id": 6}]  |
        +-----------------------------+-----------------------------+-----------------------------+---------------------------------+---------------------------------+-------------+------------+-------------+
        <BLANKLINE>
        >>> diff_result.top_per_col_state_df.show(100)
        +-----------+-------------+----------+-----------+---+-----------+-------+
        |column_name|        state|left_value|right_value| nb| sample_ids|row_num|
        +-----------+-------------+----------+-----------+---+-----------+-------+
        |         c1|    no_change|         b|          b|  3|[{"id": 2}]|      1|
        |         c1|    no_change|         a|          a|  1|[{"id": 1}]|      2|
        |         c1| only_in_left|         c|       NULL|  1|[{"id": 5}]|      1|
        |         c1|only_in_right|      NULL|          f|  1|[{"id": 6}]|      1|
        |         c2|      changed|         2|          4|  2|[{"id": 3}]|      1|
        |         c2|      changed|         2|          3|  1|[{"id": 2}]|      2|
        |         c2|    no_change|         1|          1|  1|[{"id": 1}]|      1|
        |         c2| only_in_left|         3|       NULL|  1|[{"id": 5}]|      1|
        |         c2|only_in_right|      NULL|          3|  1|[{"id": 6}]|      1|
        |         c3| only_in_left|         1|       NULL|  2|[{"id": 1}]|      1|
        |         c3| only_in_left|         2|       NULL|  2|[{"id": 3}]|      2|
        |         c3| only_in_left|         3|       NULL|  1|[{"id": 5}]|      3|
        |         c4|only_in_right|      NULL|          1|  2|[{"id": 1}]|      1|
        |         c4|only_in_right|      NULL|          2|  2|[{"id": 3}]|      2|
        |         c4|only_in_right|      NULL|          3|  1|[{"id": 6}]|      3|
        |         id|    no_change|         1|          1|  1|[{"id": 1}]|      1|
        |         id|    no_change|         2|          2|  1|[{"id": 2}]|      2|
        |         id|    no_change|         3|          3|  1|[{"id": 3}]|      3|
        |         id|    no_change|         4|          4|  1|[{"id": 4}]|      4|
        |         id| only_in_left|         5|       NULL|  1|[{"id": 5}]|      1|
        |         id|only_in_right|      NULL|          6|  1|[{"id": 6}]|      1|
        +-----------+-------------+----------+-----------+---+-----------+-------+
        <BLANKLINE>

        >>> diff_per_col_df = diff_result.get_diff_per_col_df(max_nb_rows_per_col_state=10)
        >>> from spark_frame import nested
        >>> nested.print_schema(diff_per_col_df)
        root
         |-- column_number: integer (nullable = true)
         |-- column_name: string (nullable = true)
         |-- counts.total: long (nullable = false)
         |-- counts.changed: long (nullable = false)
         |-- counts.no_change: long (nullable = false)
         |-- counts.only_in_left: long (nullable = false)
         |-- counts.only_in_right: long (nullable = false)
         |-- diff.changed!.left_value: string (nullable = true)
         |-- diff.changed!.right_value: string (nullable = true)
         |-- diff.changed!.nb: long (nullable = false)
         |-- diff.changed!.sample_ids!: string (nullable = true)
         |-- diff.no_change!.value: string (nullable = true)
         |-- diff.no_change!.nb: long (nullable = false)
         |-- diff.no_change!.sample_ids!: string (nullable = true)
         |-- diff.only_in_left!.value: string (nullable = true)
         |-- diff.only_in_left!.nb: long (nullable = false)
         |-- diff.only_in_left!.sample_ids!: string (nullable = true)
         |-- diff.only_in_right!.value: string (nullable = true)
         |-- diff.only_in_right!.nb: long (nullable = false)
         |-- diff.only_in_right!.sample_ids!: string (nullable = true)
        <BLANKLINE>
        >>> diff_per_col_df.show(truncate=False)
        +-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
        |column_number|column_name|counts         |diff                                                                                                                                    |
        +-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
        |0            |id         |{6, 0, 4, 1, 1}|{[], [{1, 1, [{"id": 1}]}, {2, 1, [{"id": 2}]}, {3, 1, [{"id": 3}]}, {4, 1, [{"id": 4}]}], [{5, 1, [{"id": 5}]}], [{6, 1, [{"id": 6}]}]}|
        |1            |c1         |{6, 0, 4, 1, 1}|{[], [{b, 3, [{"id": 2}]}, {a, 1, [{"id": 1}]}], [{c, 1, [{"id": 5}]}], [{f, 1, [{"id": 6}]}]}                                          |
        |2            |c2         |{6, 3, 1, 1, 1}|{[{2, 4, 2, [{"id": 3}]}, {2, 3, 1, [{"id": 2}]}], [{1, 1, [{"id": 1}]}], [{3, 1, [{"id": 5}]}], [{3, 1, [{"id": 6}]}]}                 |
        |3            |c3         |{5, 0, 0, 5, 0}|{[], [], [{1, 2, [{"id": 1}]}, {2, 2, [{"id": 3}]}, {3, 1, [{"id": 5}]}], []}                                                           |
        |4            |c4         |{5, 0, 0, 0, 5}|{[], [], [], [{1, 2, [{"id": 1}]}, {2, 2, [{"id": 3}]}, {3, 1, [{"id": 6}]}]}                                                           |
        +-------------+-----------+---------------+----------------------------------------------------------------------------------------------------------------------------------------+
        <BLANKLINE>
    """  # noqa: E501
    return _get_diff_per_col_df_with_cache(self, max_nb_rows_per_col_state)

DiffFormatOptions dataclass

Class used to pass formatting option when displaying a DiffResult

Source code in spark_frame/data_diff/diff_format_options.py
@dataclass
class DiffFormatOptions:
    """Class used to pass formatting option when displaying a [`DiffResult`][spark_frame.data_diff.DiffResult]"""

    nb_top_values_kept_per_column: int = 10
    """Number of most frequent values/changes kept for each column"""
    left_df_alias: str = "left"
    """Name given to the left DataFrame in the diff"""
    right_df_alias: str = "right"
    """Name given to the right DataFrame in the diff"""

left_df_alias: str = 'left' class-attribute instance-attribute

Name given to the left DataFrame in the diff

nb_top_values_kept_per_column: int = 10 class-attribute instance-attribute

Number of most frequent values/changes kept for each column

right_df_alias: str = 'right' class-attribute instance-attribute

Name given to the right DataFrame in the diff