<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yasheswi Mishra on Medium]]></title>
        <description><![CDATA[Stories by Yasheswi Mishra on Medium]]></description>
        <link>https://medium.com/@yasheswimishra?source=rss-b0a001ea3a00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NfRcSdrdbs4dN-SWpsAzDQ@2x.jpeg</url>
            <title>Stories by Yasheswi Mishra on Medium</title>
            <link>https://medium.com/@yasheswimishra?source=rss-b0a001ea3a00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:46:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasheswimishra/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Prepared and Passed the Databricks Data Engineer Professional Exam in 15 Days : Part 3]]></title>
            <link>https://medium.com/@yasheswimishra/how-i-prepared-and-passed-the-databricks-data-engineer-professional-exam-in-15-days-part-3-d8de9210e60d?source=rss-b0a001ea3a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8de9210e60d</guid>
            <category><![CDATA[azure-databricks]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Yasheswi Mishra]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 12:33:30 GMT</pubDate>
            <atom:updated>2026-04-21T12:33:30.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*bM_kfhw2xv2F51ElO9nYXw.jpeg" /></figure><p>To refer Part-1 of the Databricks Prep Series , click <a href="https://medium.com/@yasheswimishra/how-i-prepared-and-passed-the-databricks-data-engineer-professional-exam-in-15-days-part-1-ebd3faaee4c5">here</a></p><h3>Listing exam topics from most important to least important based on their relative weightage</h3><p><strong>Data Transformation, Cleansing, and Quality — 10%</strong></p><p><em>This section covers the following key touchpoints:</em></p><ol><li>Applying windowing, joins and aggregations using SparkSQL nad Pyspark to perform data transformations on large datasets processed using streaming mode or batch mode</li><li>Implementation of “Expectations” framework to quarantine bad data in Lakeflow Declarative Principles or Streaming Pipelines</li></ol><blockquote><strong>Ranking Window Functions — Refer </strong><a href="https://learn.microsoft.com/en-us/azure/databricks/sql/language-manual/sql-ref-functions-builtin#ranking-window-functions"><strong>link</strong></a></blockquote><p><em>Sample Question on Window Function : A product manager wants to understand how a user’s purchase pattern compares against purchases does by others for the same product. A data engineer writes</em></p><pre>select product_id, user_id, purchase_amount, percent_rank() over(partition by <br>product_id order by purchase amount) as purchase_position from purchases</pre><p><em>How should then product manager interpret purchase position value of 0.8 for a particular purchase?</em><br>A) The purchase amount is greater than or equal to 80 % of purchases for that product, based on rank positions<br>B)The purchase amount is 80 % of total purchase amount for that product<br>C) Purchase amount is in top 20 rows of purchases for that product<br>D) Purchase amount is exactly at 80 th percentile of all purchases for that product</p><p>Answer — A<br>Percent rank is relative rank used to express how a given value compares with others within same partition</p><blockquote><strong>Streaming Joins in Databricks</strong></blockquote><ol><li><em>How Streaming — Streaming joins behave. Refer </em><a href="https://docs.databricks.com/aws/en/notebooks/source/stream-stream-joins-python.html"><em>link</em></a></li><li><em>How Static — Streaming joins behave. Refer </em><a href="https://docs.databricks.com/gcp/en/transform/join#stream-static-joins"><em>link</em></a></li><li><em>Watermarking in stateful joins. Refer </em><a href="https://docs.databricks.com/gcp/en/structured-streaming/watermarks"><em>link</em></a></li></ol><p><em>Sample Question on Streaming joins : An FMCG Enterprise runs multiple Google Ads for its newly launched product on several applications and search engines and stores the web behaviour data in Google Analytics. The product owner is interested in having a consolidated view of all campaign ads whose ad impressions converted to clicks and also products that did not convert to clicks. As the data engineer designs a code that joins Impressions and Ads table based on adId, he observes the table growing unbounded and eventually leading to disc spills. Which of the following options would prevent table from growing unbounded while also preserving the output expectations?<br></em>A) Apply watermarking on both tables and add event time constraints and perform an inner join<br>B) Apply watermarking on both tables and perform an inner join<br>C) Enable RockDB configuration to store states of all join operations caused due to spill<br>D) Apply watermarking on both tables and add event time constraints and perform an left outer join<br>Answer — D<br>Since the requirement demands storing all ads which converted to click as well as the ones that failed to convert, we use left Outer join. It is always recommended to use watermarking and event time constraint filters to limit the growing size of the streaming table state.</p><blockquote><strong>Aggregation Operations for Advanced Transformations</strong></blockquote><ol><li><em>Different types of Output modes in Stream processing and its aggregation behaviour. Refer </em><a href="https://docs.databricks.com/gcp/en/structured-streaming/output-mode"><em>link</em></a></li><li><em>Stream aggregates and incremental aggregates. Refer </em><a href="https://docs.databricks.com/gcp/en/transform/aggregation#batch-aggregates"><em>link</em></a></li><li><em>Advanced windowing functions like Sliding Window and Tumbling window operations in Watermarking. Refer </em><a href="https://docs.databricks.com/gcp/en/ldp/stateful-processing#:~:text=Tumbling%20(fixed)%20windows%3A%20A,can%20fall%20into%20multiple%20windows."><em>link</em></a></li></ol><p><em>Sample Question 1 on Aggregation : A transactions table consisting of pre-computed aggregated KPI columns feeds a Tableau Dashboard. The BI team observes extremely slow dashboard refreshes and ask the data engineers to investigate the root cause for the slowness. The data engineers observe computations spanning to 50 minutes due to continuously arriving data in real time. Which of the following approaches should they adopt to slash the computation speeds ?<br>A) </em>df.writeStream.outputMode(“update”).toTable(“transactions”)<br>B) df.writeStream.outputMode(“append”).toTable(“transactions”)<br>C) df.writeStream.outputMode(“complete”).toTable(“transactions”)<br>D) df.writeStream.toTable(“transactions”)</p><p>Answer — (A)<br>The update mode is best-suited for the problem statement since it outputs updated values based on past microbatch and current microbatch and incrementally updates data in the final output table preventing full table re-writes. Note that complete mode here will stall the process since it re-writes entire table at every microbatch which is computationally heavy for a growing table streaming values in every minute</p><p><em>Sample Question 2 on Aggregation: A data engineering team at a large cloud services company is responsible for ensuring high availability and performance of hundreds of servers. To proactively detect unusual spikes or drops in CPU utilization that could indicate potential issues, the team decides to analyze server CPU usage. They want to capture both the minimum and maximum CPU usage during predefined intervals for each server, allowing them to quickly identify patterns of high or low utilization and trigger alerts if necessary.The team writes the following query:</em></p><pre>SELECT<br>    server_id,<br>    window.start AS window_start,<br>    window.end AS window_end,<br>    MIN(cpu_usage) AS min_cpu,<br>    MAX(cpu_usage) AS max_cpu<br>FROM server_metrics<br>GROUP BY server_id,<br>         window(event_time, &#39;10 minutes&#39;, &#39;10 minutes&#39;, &#39;3 minutes&#39;)<br>ORDER BY server_id,<br>         window_start;</pre><p><em>What is the primary purpose of this query in the context of the data engineering team’s objectives?</em></p><p>A) To calculate the metrics per server for every 3-minute interval, sliding every 10 minutes, with a 10-minute offset.<br>B) To calculate the metrics per server for every non-overlapping 3-minute interval, offset by 10 minutes<br>C) To calculate the metrics per server for every non-overlapping 10-minute interval, offset by 3 minutes<br>D) To calculate the metrics per server for every 10-minute interval, sliding every 3 minutes, with a 10-minute offset.</p><p>Answer — C<br>Since the window width is same as slide value i.e 10 minutes with an offset of 3 mins, the windowing function is non overlapping since it would create window intervals like:<br>1. 10:03–10:13<br>2. 10:13–10:23<br>3. 10:23–10:33<br>4. 10:33–10:43</p><blockquote><strong>Data Quality tracking using Expectations Framework</strong></blockquote><ol><li><em>Methods to create Quarantine table to isolate malformed records. Refer </em><a href="https://docs.databricks.com/aws/en/ldp/expectation-patterns#quarantine-invalid-records"><em>link</em></a></li><li><em>Using Lakeflow Declarative Pipelines to implement data quality checks using Expect. Refer </em><a href="https://docs.databricks.com/aws/en/ldp/expectation-patterns#schema-evolution-pattern"><em>link</em></a></li><li><em>querying quality metrics using event logs table. Refer </em><a href="https://docs.databricks.com/aws/en/ldp/monitor-event-logs#data-quality-metrics"><em>link</em></a></li><li><em>Types of data quality checks using Expectations. Refer </em><a href="https://docs.databricks.com/aws/en/ldp/expectations#action-on-invalid-record"><em>link</em></a></li></ol><p><em>Sample Question 1 on Expectations : An E-bike sharing application sends real-time telemetry data via its docking/parking stands about rides with the following schema : “ride_id string, bike_id string, user_id string, bike_speed double, batter_charge double”. A data engineer observes some malformed records in the raw table “rides_raw” that collects the streaming telemetry data such as records with “battery_charge” &gt;100 and ride_id as null. The Analytics team wants to isolate bad records into a separate table and only keep valid records in the final view feeding the dashboard. Which of the following code should the data engineer implement to create quarantined table “</em>valid_trips_data<em>” and a valid table “</em>invalid_trips_data<em>” and be able to track it using Pipeline UI or event logs ?</em></p><p><em>A)</em></p><pre>rules = {<br>  &quot;valid_ride_id&quot;: &quot;(ride_id IS NOT NULL)&quot;,<br>  &quot;valid_battery&quot;: &quot;(battery_charge&lt;=100)&quot;,<br>}<br>quarantine_rules = &quot;NOT({0})&quot;.format(&quot; AND &quot;.join(rules.values()))<br><br>@dp.view<br>def raw_trips_data():<br>  return spark.readStream.table(&quot;rides_raw&quot;)<br><br>@dp.table(<br>  temporary=True<br>)<br>@dp.expect_all(rules)<br>def trips_data_quarantine():<br>  return (<br>    spark.readStream.table(&quot;raw_trips_data&quot;).withColumn(&quot;is_quarantined&quot;, expr(quarantine_rules))<br>  )<br><br>@dp.view<br>def valid_trips_data():<br>  return spark.read.table(&quot;trips_data_quarantine&quot;).filter(&quot;is_quarantined=false&quot;)<br><br>@dp.view<br>def invalid_trips_data():<br>  return spark.read.table(&quot;trips_data_quarantine&quot;).filter(&quot;is_quarantined=true&quot;)</pre><p>B)</p><pre>rules = {<br>  &quot;valid_ride_id&quot;: &quot;(ride_id IS NOT NULL)&quot;,<br>  &quot;valid_battery&quot;: &quot;(battery_charge&lt;=100)&quot;,<br>}<br>quarantine_rules = &quot;NOT({0})&quot;.format(&quot; AND &quot;.join(rules.values()))<br><br>@dp.view<br>def raw_trips_data():<br>  return spark.readStream.table(&quot;rides_raw&quot;)<br><br>@dp.table(<br>  temporary=True<br>)<br>@dp.expect_all_or_fail(rules)<br>def trips_data_quarantine():<br>  return (<br>    spark.readStream.table(&quot;raw_trips_data&quot;).withColumn(&quot;is_quarantined&quot;, expr(quarantine_rules))<br>  )<br><br>@dp.view<br>def valid_trips_data():<br>  return spark.read.table(&quot;trips_data_quarantine&quot;).filter(&quot;is_quarantined=false&quot;)<br><br>@dp.view<br>def invalid_trips_data():<br>  return spark.read.table(&quot;trips_data_quarantine&quot;).filter(&quot;is_quarantined=true&quot;)</pre><p>c)</p><pre># Read streaming data<br>df = (spark.readStream<br>      .table(&quot;raw_trips_data&quot;))<br><br># Apply quarantine logic<br>df_transformed = (df<br>    .withColumn(<br>        &quot;is_quarantined&quot;,<br>        when(<br>            (col(&quot;ride_id&quot;).isNotNull()) &amp; (col(&quot;battery_speed&quot;) &lt;= 100),<br>            &quot;N&quot;<br>        ).when(<br>            (col(&quot;ride_id&quot;).isNotNull()) | (col(&quot;battery_speed&quot;) &lt;= 100),<br>            &quot;Y&quot;<br>        ).otherwise(&quot;Y&quot;)<br>    )<br>)<br><br># Write stream with partitioning<br>query = (df_transformed.writeStream<br>    .format(&quot;delta&quot;)<br>    .outputMode(&quot;append&quot;)<br>    .option(&quot;checkpointLocation&quot;, &quot;/chk/trips_quarantine&quot;)<br>    .partitionBy(&quot;is_quarantined&quot;)<br>    .toTable(&quot;trips_quarantine_table&quot;)<br>)</pre><p>D)</p><pre>rules = {<br>  &quot;valid_ride_id&quot;: &quot;(ride_id IS NOT NULL)&quot;,<br>  &quot;valid_battery&quot;: &quot;(battery_charge&lt;=100)&quot;,<br>}<br>quarantine_rules = &quot;NOT({0})&quot;.format(&quot; AND &quot;.join(rules.values()))<br><br>@dp.view<br>def raw_trips_data():<br>  return spark.readStream.table(&quot;rides_raw&quot;)<br><br>@dp.table(<br>  temporary=True<br>)<br>@dp.expect_all_or_drop(rules)<br>def trips_data_quarantine():<br>  return (<br>    spark.readStream.table(&quot;raw_trips_data&quot;).withColumn(&quot;is_quarantined&quot;, expr(quarantine_rules))<br>  )<br><br>@dp.view<br>def valid_trips_data():<br>  return spark.read.table(&quot;trips_data_quarantine&quot;).filter(&quot;is_quarantined=false&quot;)<br><br>@dp.view<br>def invalid_trips_data():<br>  return spark.read.table(&quot;trips_data_quarantine&quot;).filter(&quot;is_quarantined=true&quot;)</pre><p>Answer — A</p><p>The expect_all clause should be used in cases where we want to create quarantined tables. The expect all clause will only check if all records satisfy the rules without dropping rows or failing the pipelines. Option C also fulfills the condition but with the partitioning approach, we will not be able to view the data quality metrics in event logs table</p><p>That was all for Part 3 😁.. Gentle reminder to give a clap if you found the content useful or even any points of improvements in the comments are welcomed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8de9210e60d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Prepared and Passed the Databricks Data Engineer Professional Exam in 15 Days : Part 2]]></title>
            <link>https://medium.com/@yasheswimishra/how-i-prepared-and-passed-the-databricks-data-engineer-professional-exam-in-15-days-part-2-5c2550e3016d?source=rss-b0a001ea3a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c2550e3016d</guid>
            <category><![CDATA[databricks-aws]]></category>
            <category><![CDATA[azure-databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineer]]></category>
            <dc:creator><![CDATA[Yasheswi Mishra]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 17:07:27 GMT</pubDate>
            <atom:updated>2026-04-20T11:33:18.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*bM_kfhw2xv2F51ElO9nYXw.jpeg" /></figure><p>To refer Part-1 of the Databricks Prep Series , click <a href="https://medium.com/@yasheswimishra/how-i-prepared-and-passed-the-databricks-data-engineer-professional-exam-in-15-days-part-1-ebd3faaee4c5">here</a></p><h3>Listing exam topics from most important to least important based on their relative weightage</h3><p><strong>Cost &amp; Performance Optimisation – 13%<br></strong><em>This section covers the following key touchpoints:<br></em>1. Role of Unity Catalogs in reducing data redundancies and maintainence burden<br>2. Understand delta optimization techniques, such as deletion vectors and liquid clustering<br>3. Native databricks optimization techniques such as file pruning, data skipping and Z-Ordering<br>4. Implementation of CDFs in reducing delta Streaming table limitations <br>5. Using Query Profiler to identify performance bottlenecks <br>6. Identify performance issues for events like data shuffling, different types of joins and aggregation operations and ways to improve them</p><blockquote><strong><em>Unity Catalog — </em></strong><em>To prepare for Questions on Unity catalog, Databricks documentation is the best resource. One can expect questions on following topics on Unity Catalog:</em></blockquote><ul><li>UC Data Lineage capabilities for UC catalog objects — <a href="https://docs.databricks.com/aws/en/data-governance/unity-catalog/data-lineage">Link</a></li><li>Different ways to apply tagging using UC or queries — <a href="https://docs.databricks.com/aws/en/database-objects/tags">Link</a></li><li>Auto-generating AI documentation for sample tables using Unity Catalog — <a href="https://www.databricks.com/blog/announcing-public-preview-ai-generated-documentation-databricks-unity-catalog">Link</a></li><li>Controlling Egress Costs for cross-region data transfers — <a href="https://docs.databricks.com/aws/en/delta-sharing/manage-egress">Link</a></li><li>Improving Delta sharing performance using “History” — <a href="https://docs.databricks.com/aws/en/delta-sharing/create-share?language=SQL#create-a-share-object">Link</a></li><li>Using system tables such as billing, usage, audit, lineage, etc from UC to check who accessed what, check DBU consumption for objects or users and validate upstream and downstream sources(lineage) for a securables such as a notebook or a pipeline. <a href="https://docs.databricks.com/aws/en/admin/system-tables/">Link</a></li></ul><p><strong><em>Sample Question 1 on UC </em></strong><em>: A data analyst prepared Accounts_Dim table and stored it as a managed table in Unity Catalog. He asked the data engineer to set the following tags for better data discoverability:<br>layer = gold, type = PII<br>What is the best way to apply multiple tags to the managed table ?<br>A) </em>SET TAG ON TABLE catalog.schema.table (`layer` = gold` , `<em>type` = `PII`)<br>B) </em>ALTER TABLE catalog.schema.table SET TAGS (‘layer’ = ‘gold’,<br> ‘type’ = ‘pii’)<br>C) CREATE TABLE catalog_name.schema_name.table_name (Account_id INT, name STRING)<br>TBLPROPERTIES (<br> ‘delta.tags.layer’ = ‘gold’,<br> ‘delta.tags.type’ = ‘pii’);<br>D) CREATE TABLE catalog.schema.table SET TAGS (‘layer’ = ‘gold’,<br> ‘type’ = ‘pii’)</p><p>Answer — (B) <br>Option B is used when you wish to apply multiple tags on an existing table. Option C is valid but only while creating managed table</p><p><strong><em>Sample Question 2 on UC </em></strong><em>:An organization stores its orders data as streaming managed table in Unity Catalog backed by AWS S3-US-East Cloud storage and shares the table using Delta Sharing with its vendor that also happens to use Databricks for managed tables storage backed by AWS S3-Europe Cloud storage. The vendor recipient is able to view the table but is not able to perform time-travel queries on the delta table to compare order status changes for few orders over the years. What steps should the data provider take to allow the recepient to track history of the table?<br>A) </em>Run query: ALTER SHARE &lt;share name&gt; ADD Orders WITH HISTORY<br>B) Make sure CDF is enabled on the orders table and then run query:<br>ALTER SHARE &lt;share name&gt; ADD Orders WITH HISTORY<br>C)History sharing is not possible if the recipient has underlying Unity Catalog storage in a different cloud region<br>D) run query : GRANT SELECT ON Orders TO SHARE &lt;share_name&gt;<br>Answer — (B) <br>To share streaming tables via Delta-Sharing, the provide must enable CDF and then grant “history” access to the share recipient so it can perform time-travel queries. Option D) is not a viable option here since the recipient already has read access</p><p><strong><em>Sample Question 3 on UC: </em></strong><em>A data engineering team at a large organization is performing monthly financial analysis and budgeting to better understand and control their Databricks spend. As part of cost allocation across departments, they are analyzing the billing usage data available in Unity Catalog.The team wants to identify which Workload type contributed the highest DBU consumption during the current month, so they can optimize high-cost workloads and allocate budgets more effectively. Which query or approach should the data engineer use to determine the workload with the highest total DBU consumption from the billing usage table?<br>A) </em>select sku_name as ‘SKU’, sum(usage_quantity) as ‘DBUs’ from system.billing.usage where month(usage_date) = month(current_date) group by sku_name order by sum(usage_quantity) desc limit 1<br>B) select compute_type as ‘compute_type’, sum(usage_quantity) as ‘DBUs’ from system.access.audit where month(usage_date) = month(current_date) group by compute_type order by sum(usage_quantity) desc limit 1<br>C) select sku_name as ‘SKU’, sum(usage_quantity) as ‘DBUs’ from system.billing.usage group by sku_name order by sum(usage_quantity) desc limit 1<br>D) select compute_type as ‘compute_type’, sum(usage_quantity) as ‘DBUs’ from system.billing.usage where month(usage_date) = month(current_date) group by compute_type order by sum(usage_quantity) desc limit 1<br>Answer — (A)<br>The usage table in the billing schema is used to define metrics such as DBU consumption per workload type or for each user at particular datetime. It can also be used to find compute costs of each Unity catalog object, job ID or notebook ID. In usage table, “SKU” column specifies the workload type that consumes DBUs and could have these distinct values:<br>a. Jobs Compute<br>b. Serverless Compute<br>c. Lakeflow Declarative Principle<br>d. Predictive Optimization<br>e. Model Fine-tuning<br>Refer this link for a broader <a href="https://docs.databricks.com/aws/en/admin/system-tables/billing">view</a> of usage table</p><blockquote><strong>Deletion Vectors — </strong>Questions on how Deletion vectors phenomena behaves when enabled for delta tables. Refer <a href="https://docs.databricks.com/aws/en/delta/deletion-vectors">link</a></blockquote><p><strong><em>Sample question on Deletion vectors</em></strong><em> : A sales delta file loaded to ADLS Gen 2 was found to be having duplicate records breaking primary key logic. Hence, a senior engineer suggests to remove duplicate records without hampering the day-to-day scheduled run of sales pipeline. Hence he enables delta.enableDeletionVectors table property triggering deletion vectors files in the Data lake storage. From the below options, select the option that best dictates the behaviour of deletion vectors after it is enabled.<br></em>A) The rows that should be deleted will be marked in the same delta file and will be physically deleted from the new version files in the next load operation<br>B) The rows that should be deleted are stored in a small file called “deletion_vectors” , triggering a new delta file version where the rows from deletion_vectors file will be physically deleted in the new version<br>C) The delta.enableDeletionVectors will run liquid clustering and re-write the entire file in a new version with deleted rows present but marked as soft-delete<br>D) The rows that should be deleted are stored in a small file called “deletion_vectors” which later will be soft- deleted in the next load operation and eventually deleted physically during the routine “OPTIMIZE” command run</p><p>Answer — (D)<br>Deletion vector files store only those rows that were updated or deleted. These rows are skipped when the delta file is subsequently read without re-writing the entire file. These deleted rows will be marked in the newer file versions with the help of deletion_vectors file. These rows would finally be physically deleted and re-written when “OPTIMIZE” or Auto-compaction commands are ran on the entire table. Thus, deletion vectors prevents re-writing the file everytime there is a DML operation</p><blockquote><strong><em>Delta Optimization techniques</em></strong><br>- Understanding Liquid clustering and how it optimizes delta file layout using predictive optimization. Refer <a href="https://docs.databricks.com/aws/en/delta/clustering">link</a><br>- Z-Ordering using Optimize. Refer <a href="https://docs.databricks.com/aws/en/sql/language-manual/delta-optimize">link</a><br>- Auto-Optimize and Auto-compaction and advantages over tradition “Optimize” command. Refer <a href="https://docs.databricks.com/aws/en/delta/tune-file-size#:~:text=Auto%20compaction%20and%20optimized%20writes%20each%20reduce%20small%20file%20problems,clustering%20for%20enhanced%20data%20skipping.">link</a><br>- Understanding Delta lake file statistics for data skipping. Refer <a href="https://docs.databricks.com/aws/en/delta/data-skipping">link</a><br>- Advantages of Vaccum command for Data retention. Refer <a href="https://docs.databricks.com/aws/en/sql/language-manual/delta-vacuum#parameters-1">link</a><br>- Transaction log structure in Delta Files. Refer <a href="https://www.databricks.com/blog/2019/08/21/diving-into-delta-lake-unpacking-the-transaction-log.html">link</a></blockquote><p><strong><em>Sample question 1 : </em></strong><em>A product team observes that a transactional table’s reading latency has degraded significantly over the years. Analysts use high-cardinality columns to apply filters which makes file scanning extremely slow. These filtering columns keep on changing with time. Also, few of the data engineers have observed skew within partitions in the delta file where one partition is significantly larger than the others. From the below options, which the most efficient approach that would reduce latency of the table?<br></em>A) Apply Z-Ordering on all columns that are used as filters to reduce file scanning time<em><br>B) </em>Apply Auto-Optimize during file ingestion and Auto-compaction after files have been loaded to eliminate small files problem <br>C) Apply predictive optimization on the table as this feature would continuously learn from table’s querying behaviour and change the data layout periodically to output reads more efficiently<br>D) Enable Automatic liquid clustering on the table to get rid of performance issues like partition skew, small files and changing query behaviour<br>Answer — (D)<br>Auto Liquid Clustering is a replacement for both partitioning and Z-ordering, and they can’t be used simultaneously on the same Delta table. Liquid Clustering automatically runs necessary data layout operations like Optimize, Vaccum and Predictive optimization to re-shuffle everytime it observes change in querying patterns</p><p><strong><em>Sample question 2</em></strong><em> : A tobacco retail client decides to retain its sales transactional files only upto 30 days old in ADLS Gen3 cloud storage. Any data or files older than 30 days must be purged. Which of the follwing commands should be enabled to achieve this objective ?<br></em>A) No need to make changes to “Vaccum” property as the default retention period of delta files is 30 days<br>B) run query : ALTER TABLE sales SET TBLPROPERTIES (‘delta.deletedFileRetentionDuration’ = ’30 days’);<br>C) set spark.databricks.delta.retentionDurationCheck.enabled to False and then run “ VACUUM sales RETAIN 720 HOURS”<br>D) run query : “ VACUUM sales RETAIN 30 days”<br>Answer — (B)<br>For an existing table, one change change retention period using “ALTER” command. spark.databricks.delta.retentionDurationCheck.enabled is set to True by default. One must set it to false only when you want the retention check to be less than 7 days. “ VACUUM sales RETAIN 30 days” is the incorrect option since we need to mention retention period in hours while using VACCUM command directly in a query</p><p><strong><em>Sample Question 3</em></strong><em> : What is the default file size that Auto-Optimize and Auto-Compact try to achieve by merging small files into files with more or less the same size?<br></em>A) 128 mb<br>B) 1 GB<br>C) 256 MB<br>D) No such default file size. It tries to create different sized files by grouping similar data</p><p>Answer — (D) <br>The default file size that Auto-Optimize tries to achieve is 128 MB as against the 1 GB default file size used by the traditional “Optimize” command</p><p><em>Sample Question 4 : Which of the below statements perfectly define the advantages of Checkpoints file in Transaction log folder of a Delta file ?<br></em>A) It is used to store the state of the previous version to prevent duplication or data loss<br>B) It logs on Deletes, Updates on Insert operations activities for any version of the delta file<br>C) the checkpoint file is created after every 10th commit in the transaction_log table to process current table version state at a faster speed<br>D) It stores row groups and footer details for every parquet file helpful for data skipping<br>Answer — C<br> Delta Lake automatically generates checkpoint as needed to maintain good read performance<strong>. T</strong>hey offer the Spark reader a sort of “shortcut” to fully reproduce a table’s current state that allows Spark to avoid reprocessing thousands of tiny, inefficient JSON files</p><blockquote><strong><em>Change Data Feed ( CDF) — </em></strong>A very important feature in Apache Spark Streaming that allows delta files to perform row level changes instead of file level changes avoiding full table re-writes while also maintaining “append-only” nature of Spark Streaming tables. Topics of interest :</blockquote><ol><li><em>CDF specific functionalities like “table_changes”, “change_data” folder structure created after CDf enablement. Refer </em><a href="https://docs.databricks.com/aws/en/delta/delta-change-data-feed"><em>here</em></a></li><li>Differences between CDF and CDC</li></ol><p>3. When and when not to use CDF</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*JBcm4E7ZHyGAxq_z1E3GaQ.png" /></figure><p><strong><em>Sample Question on CDC</em></strong> : <em>An Ecommerce giant receives its invoice data with schema ‘Invoice_ID string, invoice_status string, invoice_date timestamp, discount_amount double’ from Shopify server which streams into raw table named invoice_bronze which is further migrated to invoice_silver table where CDF is enabled. The team needs to incrementally propogate invoice updates to the target table with entire updates history retained. Which of the following options would be convenient to achieve the requirement ?<br></em>A) use ```spark.read.format(“delta”).option(“readChangeFeed”, “true”)<br> .option(“startingVersion”, 0).table(“<em>invoice_silver</em>”))``` followed by “Merge INTO” to incrementally load changes into the target table</p><p>B) use ```spark.readStream.format(“delta”).option(“readChangeFeed”, “true”).option(“startingVersion”, latest).table(“<em>invoice_silver</em>”))``` followed by “Merge INTO” to incrementally load changes into the target table</p><p>C) use ```spark.readStream.format(“delta”).option(“readChangeFeed”, “true”).option(“startingVersion”, latest).table(“<em>invoice_silver</em>”))``` followed by AutoCDC APIs with SCD Type 2 enabled</p><p>D) use ```spark.readStream.format(“delta”).option(“readChangeFeed”, “true”).option(“startingVersion”, latest).table(“<em>invoice_silver</em>”)).writeStream<br> .format(“delta”)<br> .outputMode(“append”)<br> .option(“checkpointLocation”, “/chk/invoice_dim”)<br> .table(“target_table”)```</p><p>Answer — C<br>Since the requirement is to incrementally preserve history, Auto CDC with SCD Type 2 enabled is the best option since it will not require manually using “MERGE INTO” to propogate incremental updates. Option A here is completely wrong since it performs batch processing and would perform full refresh for every run. Option B could also be suitable for the use-case but requires additional effort to customize query with “MERGE INTO” and SCD Type 2 columns manually</p><blockquote><strong><em>Query Profiler — </em></strong><em>Refer </em><a href="https://docs.databricks.com/aws/en/sql/user/queries/query-profile"><em>link</em></a><em> to access resources on Query Profiler and prepare for questions on following:<br></em>1. Query Summary Page — Metrics like Wall Clock Duration, Query Source, Query status, Query statement and Aggregated task time<br>2. Query Details Page — Query Summary, Top operators and Query Text</blockquote><p><em>Sample Question on Query Profiler : A data engineer executed a query that took a long time. To investigate, they use the Query Profiler associated with this query to check the Total wall-clock duration metric.Which of the following statements correctly describe what this metric measures?<br>A) </em>The total time spent on query optimization and file pruning<br>B) he total time from the start of scheduling to the end of query execution<br>C) The time spent on actual query execution<br>D) The time spent on query scheduling</p><p>Answer — (B)<br>The Total wall-clock duration metric measures the total time from the start of scheduling to the end of query execution, covering the entire period the query takes to run, including scheduling, optimization and file pruning, and actual execution.</p><blockquote><strong>Identify Performance bottlenecks during Spark shuffle operations<br></strong>1. Performance issues during Joins and measures to improve it. Refer <a href="https://docs.databricks.com/aws/en/transform/optimize-joins">link</a><br>2. Causes of data spill and their effects on compute performance. Refer <a href="https://www.databricks.com/discover/pages/optimize-data-workloads-guide#data-spilling">link</a><br>3. Data shuffling effects on computation costs and performance. Refer <a href="https://www.databricks.com/discover/pages/optimize-data-workloads-guide#data-shuffling">link</a></blockquote><p><em>Sample Question : A data engineer observes a spark job taking longer than usual while performing a join between 2 tables. On investigating the issue on Spark UI, he observes an executor processing the task longer than the rest of executors. He suspects this behaviour is due to skewness caused by a joining key containing disproportionately higher records than the others. Which of the follwing options would have no effect on reducing skewness on the join operation ?<br></em>A) perform broadcast join between both tables<br>B) perform salting on skewed joining key to reduce processing time on the executor<br>C) increase number of partitions using spark.sql.shuffle.partitions<br>D) Enable Adaptive Query Execution on the spark job</p><p>Answer — A)<br>Broadcast joins do not resolve skew caused by uneven key distribution, as the skewed key still results in uneven workload across partitions. Other specified options are viable options to reduce skewness</p><p>Thankyou so much for reading the article :) <br>If you found the content helpful during the preparation, please reward me with a clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c2550e3016d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Prepared and Passed the Databricks Data Engineer Professional Exam in 15 Days : Part 1]]></title>
            <link>https://medium.com/@yasheswimishra/how-i-prepared-and-passed-the-databricks-data-engineer-professional-exam-in-15-days-part-1-ebd3faaee4c5?source=rss-b0a001ea3a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd3faaee4c5</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[azure-databricks]]></category>
            <category><![CDATA[databricks-exam]]></category>
            <dc:creator><![CDATA[Yasheswi Mishra]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 16:58:08 GMT</pubDate>
            <atom:updated>2026-04-18T14:52:33.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*DLlb6hxubTqU8pIGUPQxXA.png" /><figcaption>Badge</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*bM_kfhw2xv2F51ElO9nYXw.jpeg" /></figure><p>If you’re working for a Fortune 500 company or any Product based MNC as a data engineer, there is a 60 % chance you will need to adopt Big data Processing and warehousing skills using Databricks. Hence, getting certified in it will be a great boost to your resume . Lets sum up topics that constitute scenario-based questions in Databricks Professional certification along-with resources and sample questions that would make you exam-ready in a week or two !!</p><blockquote>Tips and Tricks before moving to the topics :</blockquote><ol><li>Follow closely all videos and notes from Virtual festival</li><li>Refer Databricks official documentation as your main source of preparation for the exam</li><li>Only 1 option would be the correct one. If there are more than 1 correct options, it would be specified in the question</li><li>You can subscribe to the following courses on Udemy by Derar Hussain:<br>a. <em>Databricks Certified Data Engineer Professional — Preparation<br>b. Practice Exams: Databricks Certified Data Engineer Professional</em></li></ol><p>5. You will be encountered with following types of questions:<br> a. Scenario-based questions largely based on Spark Structured Streaming<br> b. Code completion questions ( Pyspark and SQL)<br> c. Databricks functionalities use-cases — theoretical<br> d. Identify and explain the behavior of a Databricks function argument (e.g., Auto Loader’s pathGlobFilter)<br> e. Choosing option with correct code to achieve the specified business requirement</p><p><strong>Exam Pre-Requisites</strong></p><p>Exam Fee — 200 $ ( Get 100 $ Off by attending Databricks Virtual Festival and finishing the required modules, track virtual festival updates <a href="https://community.databricks.com/t5/learning-events/databricks-learning-festival-self-paced-global/ev-p/150223">here</a>)</p><p>2. Exam Duration — 2 Hours</p><p>3. Number of Questions — 60</p><p>4. Passing Score — 75 % or above</p><h3><strong>Listing exam topics from most important to least important based on their relative weightage</strong></h3><blockquote><strong><em>Developing Code for Data Processing using Python and SQL — 22% (Carries the highest weightage) <br></em></strong>This section covers the following key touchpoints:</blockquote><ol><li>how Auto CDCs ,Lakeflow Declarative Principles ( LDP ) and Autoloaders are used to build Streaming or Batch pipelines.</li><li>creation of Lakeflow Jobs using UI/Rest APIs/ CLI</li><li>developing efficient Python project structure to deploy DABs for CI-CD integration.</li><li>Managing Third party libraries for installing Python packages</li><li>Developing UDFs</li><li>Developing Unit tests and Integration tests using Python modules</li></ol><blockquote><strong><em>Auto-CDCs: </em></strong>Refer the <a href="https://docs.databricks.com/aws/en/ldp/cdc?utm_source=chatgpt.com">link</a>. Questions asked: —</blockquote><p><em>a. SequenceBy Clause used inside Auto-CDC sql Queries<br>b. Functioning of SCD Type0, Type1 and Type2 <br>c. Advantages of Auto-CDCs over Traditional CDCs<br>d. Table structure after applying AutoCDCs : _START_AT, _END_AT, etc<br>e. Deleting duplicates, updating rows using AutoCDCs and effect on Spark Streaming tables</em></p><p><em>Sample Question on Auto-CDC: </em><strong><em>An E-commerce giant has streaming data about its product inventory flowing every hour into a cloud Data Lake storage with schema “product_id string, event_timestamp datetime, product_name string”. A junior data engineer observes multiple records of same product_ids logged at different event_timestamps in same as well as subsequent microbatches flowing in products_bronze table with SCD Type 2 enabled. Which of the following code would be well-suited to get rid of duplicate product_ids while migrating product_bronze into products_silver table and keep unique product_ids only with the latest changes to preserve the nature of the silver layer?<br></em>a)</strong> MERGE INTO products_silver t USING STREAM(products_bronze) s<br>ON t.product_id= s.product_id WHEN MATCHED AND t.event_timestamp&lt; s.event_timestamp THEN UPDATE SET *<br> WHEN NOT MATCHED THEN INSERT * SEQUENCE BY s.event_timestamp<br><strong>b)</strong> MERGE INTO products_silver t USING products_bronze s<br>ON t.product_id= s.product_id WHEN MATCHED THEN UPDATE SET *<br> WHEN NOT MATCHED THEN INSERT * <br><strong>c) </strong>CREATE FLOW flowname AS AUTO CDC INTO products_silver FROM stream(products_bronze) KEYS (product_id) APPLY AS DELETE WHEN operation_type = “DELETE” SEQUENCE BY event_timestamp COLUMNS * EXCEPT (operation_type , event_timestamp) STORED AS SCD TYPE 1;<br><strong>d)</strong>CREATE FLOW flowname AS AUTO CDC INTO products_silver FROM stream(products_bronze) KEYS (product_id) APPLY AS DELETE WHEN operation_type = “DELETE” SEQUENCE BY event_timestamp COLUMNS * EXCEPT (operation_type , event_timestamp) STORED AS SCD TYPE 2 <strong>ANSWER</strong>: ( C )<br>Options A and B are manual CDC queries that need the usage of “MERGE INTO” statements. Considering the scenario, as multiple updates and late records are incoming in every stream for the same product, “Sequence By” keyword should be used to determine the product_id with the latest update. However, Traditional CDCs do not support “Sequence By”. Auto-CDCs under LDP ( LDP triggered by “Create Flow”) are very efficient at implementing “Sequence By” and eliminate the need to write MERGE statements manually. Here D option is also not valid as the requirement is to only keep unique product_id per product with the latest update which can be achieved through SCD Type 1 processing.</p><blockquote><strong><em>Auto-loaders </em>— </strong>Refer this <a href="https://docs.databricks.com/aws/en/ingestion/cloud-object-storage/auto-loader/schema">link</a>.Following questions asked :<br><em>a. Python Syntax to read cloud files using AutoLoader<br>b. arguments used to read cloud files and their uses : PathGlobFilter, Checkpointing, schemaLocation, etc<br>c. Different types of schema evolution modes</em></blockquote><p><em>Sample Question on Auto-loader: </em><strong><em>An ETL Pipeline tracks and loads image files on Amazon S3 using Autoloader. The senior data engineer had been observing failures lately while reading from these unstructured files due to change in schema .Which of the following schema evolution modes should be implemented so that pipeline reverts to the old schema that existed before failures,without keeping any additional columns that might be created due to schema drift?</em></strong><em><br>A ) </em>spark.readStream.format(“cloudFiles”).option(“cloudFiles.format”, &lt;source_format&gt;).option(“cloudFiles.schemaEvolutionMode”,”addNewColumns”).option(“cloudFiles.schemaLocation”,“/mnt/schema”).load(&lt;filepath&gt;)<br>B ) spark.readStream.format(“cloudFiles”).option(“cloudFiles.format”, &lt;source_format&gt;).option(“cloudFiles.schemaEvolutionMode”,”rescue”).load(&lt;filepath&gt;)<br>C ) spark.readStream.format(“cloudFiles”).option(“cloudFiles.format”, &lt;source_format&gt;).option(“cloudFiles.schemaEvolutionMode”,”failOnNewColumns”).load(&lt;filepath&gt;)<br>D ) spark.readStream.format(“cloudFiles”).option(“cloudFiles.format”, &lt;source_format&gt;).option(“cloudFiles.schemaLocation”,“/mnt/schema”).schema(&lt;my schema&gt;).load(&lt;filepath&gt;)<br>Answer — ( D ) <br>When you do not define a particular schema evolution mode and no explicit schema, usually the default becomes “addToNewColumns”. addToNewColumns infers the schema of the microbatch to add the new columns, on the other hand “rescued” mode creates a column to store new columns as a json string . But for out requirement, as we do not want the pipeline to add any new column, we will use option D. If you do not provide a specific evolution mode and an explicit schema, the schema evolution mode will be set to “none” and will strictly follow the provided user-defined schema</p><blockquote><strong><em>Lakeflow Jobs — </em></strong>Refer <a href="https://docs.databricks.com/aws/en/jobs/dynamic-value-references">link</a>. Questions on: <br>a. task types for job creation: ForEach, if-else, etc<br>b. job trigger methods: Scheduled, Cron Syntax, Triggered, etc<br>c. Job CLI/RestAPI commands to create or deploy a job:Refer <a href="https://docs.databricks.com/api/workspace/jobs/getpermissions">here</a><br>d. parameterization of job values and task values : Refer <a href="https://docs.databricks.com/aws/en/jobs/dynamic-value-references">here</a></blockquote><p><em>Sample Question on Lakeflow Jobs: </em><strong><em>A lakeflow job runs using 2 Notebooks: Notebook A and Notebook B using an if-else condition task condition {job.start_time.is_weekday} which means if the current day is a weekday run Notebook A , If current day is a weekend run Notebook B. What action should be taken by senior data engineer before approving the PR ?<br></em></strong>A) The {job.start_time.is_weekday} dynamic value reference does not exist. It should be changed to {job.start_time.iso_weekday}<br>B) No action is needed. The data engineer should merge the PR<br>C) The {job.start_time.is_weekday} dynamic value reference does not exist. It should be changed to {job.start_time.day_of_week} to determine if the present day is weekday or weekend<br>D) Databricks Lakeflow job does not any conditional check to determine if today is weekend or weekday. The data engineer should use cron syntax while setting scheduled triggers for the job<br>Answer — (B)<br>Lakeflow jobs does provide a dynamic value referencing method called “is_weekday” which returns true if the day is a weekday. “iso_weekday” is is not applicable here as it returns digit from 1 to 7, representing the day of the week of the timestamp. Lastly “day_of_week” does not exist.</p><blockquote><strong><em>LDP</em></strong> : Refer <a href="https://docs.databricks.com/aws/en/ldp/flows">link</a>. Questions asked:<br>a. LDP decorator objects like streaming tables, materialized views and temporary views and its use cases<br>b. “Dry run” functionality in LDP<br>c. LDP with Auto-CDCs to create bronze-silver-gold tables</blockquote><p><em>Sample Question 1 on LDP : </em><strong><em>A semiconductor MNC collects streaming data emitted from sensors using Lakeflow Declarative Pipelines in a serverless Databricks cluster. The streaming data is collected in the bronze layer with columns “task_id, process_id, task_time, task_status”. Subsequent streams keep sending updated records for same task ids. A requirement has come up which requires a new column from a static table with columns “process_id, process_name” to be joined to the bronze table ensuring there are no duplicate task ids. How can this be achieved using LDP ?<br></em></strong>A) read static table as a delta managed table and join with the bronze streaming table in the silver layer and apply row_number function to only keep task ids with latest updates storing the target table in gold layer<br>B) read static table as a temporary view, remove duplicate task ids in bronze table by using Auto CDCs and store de-duplicated data in silver layer. Finally perform a join between the temporary view and streaming silver table and store the target as a materialized view in gold layer<br>C) remove duplicate task ids in bronze table by using Auto CDCs and store de-duplicated data in silver layer. In the gold layer, load the static table as a managed table and perform the streaming-static join storing target directly to unity catalog because using materialized views lead to high latencies since LDP does not allow incremental refresh of materialized views <br>D) Use “MERGE INTO” in LDP to get rid of duplicate task ids and use the de-duplicated table to join with static table in the gold layer<br>Answer — (B)<br>LDP automates the preserving of task ids with latest changes using “SequenceBy” clause, eventually catering to our use-case. It is always recommended to store a satic table as a temporary view in LDP to simplify streaming-static joins. Materialized views could eventually be used to perform the final join since serverless clusters allow incremental refresh of materialized views reducing latency in populating target table</p><p><em>Sample Question 2 on LDP : </em><strong><em>A user created LDP pipeline using “create flow cdc flow” sql query logic and incorporated sequenceBy parameters to manage incremental or late-arriving updates. The result of the pipeline is stored in users_target. After running the pipeline, he observes 2 new objects created in the metastore along with the target table. <br>- A view named users_target<br>- A table named __apply_changes_storage_users_target<br>Which of the following correctly explains the purpose of these objects?<br></em></strong>A) The view users_target is a materialized snapshot of the raw data, while the table __apply_changes_storage_users_target stores user activity logs for auditing purposes<br>B) These objects are used for internal CDC processing leveraging sequence_by along with extra information such as, tombstones and versions required to handle out-of-order data.<br>C) The view users_target and the table apply_changes_storage_users_target are temporary objects created for write optimization and are deleted immediately after the pipeline runs.<br>(D) The users_target view is a virtual index on the target table to speed up queries, and __apply_changes_storage_users_target is a backup of the original users_target index<br>Answer — (B) <br>In Lakeflow Declarative Pipelines*, when you create a CDC (Change Data Capture) flow with operations like Apply As Delete and SequenceBy, the system needs a way to manage incremental updates, including insertions, updates, and deletions, while maintaining the correct order of events based on sequence keys. The __apply_changes_storage_users_target table is an internal storage table that keeps track of these changes along with “tombstone” markers for deleted rows and versioning metadata to ensure that out-of-order or late-arriving events are applied correctly. This internal table is not meant for direct querying but is essential for maintaining CDC consistency. The users_target view, on the other hand, is a virtual layer over this internal table that presents the current state of the data as a clean, queryable snapshot. This allows the CDC logic to remain encapsulated and transparent.</p><blockquote><strong><em>Spark UDFs </em></strong><em>—</em>Questions asked :<br>a. Different Pyspark built-in higher order functions like transform,coalesce, withColumn, etc: Refer <a href="https://api-docs.databricks.com/python/pyspark/latest/pyspark.sql/api/pyspark.sql.DataFrame.withColumn.html">here</a><br>b. Pandas UDF functions like applyInPandas, pandas decorator functions<br>c. Different methods to apply Spark UDF functions to a dataframe: <a href="https://docs.databricks.com/aws/en/udf/python">Link</a></blockquote><p><em>Sample Question : </em><strong><em>A data engineer at a retail company is tasked with analyzing daily sales trends across hundreds of stores. The raw PySpark DataFrame contains columns store_id, date, and sales_amount. The engineer wants to calculate a 7-day rolling average of sales per store, leveraging Pandas for its convenient rolling window operations. To achieve this task, the engineer created a custom Python function called “calculate_sales” where the input and output of the function are both pandas.DataFrame.Which of the following allows applying this function to each group of store_id while preserving Spark efficiency?<br></em></strong>A) df.mapInPandas(“store_id”, calculate_sales, schema)<br>B) df.groupBy(“store_id”).applyInPandas(calculate_sales, schema)<br>C) df.selectExpr(“calculate_sales(store_id)”)<br>D) pandas_udf(calculate_sales, returnType=Series)<br>Answer — (B)<br>The applyInPandas function, used after a groupBy operation, is designed exactly for this scenario: applying a Python function that takes and returns a Pandas DataFrame to each group of data within a Spark DataFrame, while preserving state variables that are local to each group&#39;s processing logic.</p><blockquote><strong><em>Development of Testing pipelines for maintaining data quality:</em></strong></blockquote><p><em>a. types of tests : Unit, Integration, End-to-End<br>b. Dataframe Equality test functions using Pytest. Eg: AssertDataFrameEqual, assertSchemaEqual, etc. Refer </em><a href="https://www.databricks.com/blog/simplify-pyspark-testing-dataframe-equality-functions"><em>here</em></a><em><br>Sample Question :</em><strong><em> Which of the following tests is not considered a valid standard test to determine the correctness of the application or the components or low level objects included in the application?</em></strong><em><br></em>A) Unit testing<br>B) Integration testing<br>C) Dry-run testing<br>D) End to End testing<br>Answer — C<br>Unit test test if implemented functions are notebooks are working as expected. Integration test tests the integration between 2 or more modules. E2E Testing tests the entire application by simulating user experience. Dry run here is not a valid test as it is used in Delta Live tables to validate your pipeline without actually running it or processing data.</p><blockquote>Installing third party python libraries : Refer <a href="https://docs.databricks.com/aws/en/init-scripts/">link.</a> Questions asked:</blockquote><p>a. different ways to install PyPI packages like init file and %pip<br>b. installing packages as cluster-scoped or notebook-scoped<br>c. Installing packages from Volume, Workspace or DBFS</p><p><em>Sample Question : </em><strong><em>A python .whl binary file package is located on the local user directory. How to ensure that this package file will be automatically installed whenever a cluster restarts ?</em></strong><em><br></em>A) Upload the .whl file directly to DBFS <br>B) Store the .whl file to Volumes so it becomes part of Unity Catlog and everyone can access it<br>C) Specify %pip install &lt;filename&gt; on every notebook where you need this package<br>D) add init script to the repo workspace and make it cluster-scoped<br>Answer — (D)<br>While “%pip install” is also one way to install python packages, it needs to be ran on every notebook that uses it, same goes for package files stored on Volumes where they will be installed every time a user references it. Using DBFS is okay for interactive clusters but would not work on production environments. The most efficient method here is to use init script as they would install the library on every node as soon as the cluster starts</p><h4>Closing Points :</h4><p>The above sample questions directly reflect the actual questions that were asked in the exam. Make sure to learn and observe behavior of Spark Streaming under different states as this section would majorly cover spark streaming fundamentals and how they work under different requirements.</p><p>If you found the article helpful, please give a clap and share it with your friends who are preparing for this exam. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd3faaee4c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Messy Raw Tables to Business-Ready Data: A Data Engineer’s Transformation Playbook]]></title>
            <link>https://medium.com/@yasheswimishra/from-messy-raw-tables-to-business-ready-data-a-data-engineers-transformation-playbook-5352621c10f8?source=rss-b0a001ea3a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/5352621c10f8</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Yasheswi Mishra]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 06:44:37 GMT</pubDate>
            <atom:updated>2026-04-03T18:37:03.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3_yibYo0ElY_Mfe-wdGAg.png" /></figure><blockquote>In this article, I will walk you through the data engineering strategies I used for Lendingkart Dataset sourced from Kaggle. This article consists of the transformation stages that occur in a data-engineering project life-cycle while working on a project in a fintech/banking industry. We would be using distributed computing technologies to achieve desired project outcomes</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*xgTzVzimJ5Cz1wFmmVM5TA.png" /></figure><p>Lendingkart is a Fintech company with a Peer-to-Peer business model that provides an interface to loan borrowers and loan providers to provide/take loans by applying advanced data analytics and machine learning to assess creditworthiness and streamline the loan approval process, enabling faster disbursals compared to traditional banks.</p><p>As a data engineer working at Lendingkart, you will be encountered with various tasks that should align with the business objective of the project. This article will cover the following few aspects that a data engineer will work on in order to deliver results that capture the use-case provided by the stake-holders :<br>1. Identifying and understanding the business objective or Problem Statement<br>2. Applying data normalization for data integrity<br>3. Perform data cleaning <br>4. Identifying and reporting bad data<br>5. Perform data processing (Loan score KPI calculation)</p><p>Find entire loans dataset and the metadata describing each field <a href="https://www.kaggle.com/datasets/adarshsng/lending-club-loan-data-csv?select=LCDataDictionary.xlsx"><em>here </em></a><em><br></em>Data overview:<br>1. Format of data — CSV<br>2. Size of data — 1.6 GB (2 million rows, 118 columns)<br>3. Primary key column — <em>id (</em>renamed to<em> loan_id)</em></p><p>The CSV file is stored in HDFS and loaded via a Apache Spark Session through Jupyter Notebook in interactive mode. I will be using Pyspark to perform data manipulation and calculate KPIs</p><blockquote>1. Identifying and understanding the business objective or Problem <em>Statement</em></blockquote><p>The primary objective of the project is to determine whether a loan application from a borrower should be approved or rejected based on various attributes in the dataset.<br>The role of a data engineer in this project would be to perform data cleaning and pre-processing and calculate loan score to determine the credibility of a loan application or a loan borrower. This data will, then be made available to the AI-ML team to perform supervised machine learning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*K7pTC9f-ZUC9acTJWKW9Yg.png" /></figure><blockquote>2. Applying data normalization for data integrity</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6yM83jJIiRafmoLoaBJwQ.png" /><figcaption>Raw Data Snapshot</figcaption></figure><p>Before segregating the single raw CSV file into normalized dataframes, a data preprocessing activity here becomes indespensable. As we can see from the snapshot, the <em>member_id </em>column is null. This column represents the ID of the borrower. In the Kaggle dataset, this column was masked and had only null values but we will be populating this column with values as this column attribute is necessary for KPI calculations<br><strong><em>Handling Nulls in member_id column:-</em></strong><em><br>1. Logically speaking, one member/loan borrower can apply for multiple loans. Thus, one member_id can be linked to various loan_ids(loan_id here is the column “id” later re-named to loan_id)<br>2. We can determine whether multiple loan_ids are linked to one member or not using some fields that determine the profile of the loan borrower/member. These fields are :<br></em>a<em>. </em>emp_title <br>b. emp_length<br>c.home_ownership<br>d. annual_inc<br>e. zip_code<br>f. addr_state<br>g. grade<br>h. sub_grade<br>i. verification_status<br><em>3. If multiple rows have same values in above columns, it infers a repeating member who has applied for multiple loans. To replace nulls with a meaningful value that logically represents the id of a member, we use </em><strong><em>sha </em></strong><em>function that computes unique fixed-size hash value of a given input column. In our case, the input to this hash function would be the 9 columns mentioned above that encapsulate the profile of the member.</em></p><pre>from pyspark.sql.functions import sha2,concat_ws<br>lendingClub_df=spark.read.format(&quot;csv&quot;).option(&quot;header&quot;,&quot;true&quot;).option(&quot;inferSchema&quot;,&quot;true&quot;).load(&quot;&lt;hdfs_path&gt;&quot;)<br>lendingClub_df=lendingClub_df.withColumn(&quot;member_id&quot;, sha2(concat_ws(&#39;||&#39;,*[&#39;emp_title&#39;,&#39;emp_length&#39;,&#39;home_ownership&#39;,&#39;annual_inc&#39;,&#39;zip_code&#39;,&#39;addr_state&#39;,&#39;grade&#39;,&#39;sub_grade&#39;,&#39;verification_status&#39;]), 256))<br>lendingClub_df.select(&quot;member_id&quot;).show(truncate=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*_q7dHr6PghCMiMCKFQgmvA.png" /><figcaption>member_id column populated with hash value</figcaption></figure><p><em>4. After the member_id column has been replaced with the hash values in the above code, one can check if there are any repeating member_ids indicating one member applying for more than 1 loans</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*xg5m0FQm4l1AFSDzqD5UFQ.png" /><figcaption>member_ids with multiple loans</figcaption></figure><p><em>P.S — From the above snapshot, the member_id whoc applied for a loan application 33 times can be considered an outlier since it seems highly unlikely that the company would allow a person to allow for this many loan applications multiple times in a given time period. On investigating further, we see that all 33 rows were nulls hence the sha2 logic considered it to be the same member. Thus, we drop these rows beforehand before normalizing the file</em></p><ul><li>Once we have <em>member_id </em>column populated, we can break down one large table into 4 normalized CSV files:<br>1. Customers table— Contains information about the loan borrowers. Contains the following fields with primary key as member_id:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2X1NJh0TAXKIpyu6378MXg.png" /><figcaption>Fields in customers data</figcaption></figure><p>2. Loans Table — Contains records about all the loans rolled out by the institution or the loan provider. Contains the following fields with primary key as id(renamed to load_id):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXuRUW1EGJJdDPApwoc8ow.png" /><figcaption>Fields in loans data</figcaption></figure><p>3. Loans_Repayments — Contains records about all the loans re-paid by the loan borrower at a given time. Contains the following fields with primary key as id(renamed to load_id):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*_7Orw-DTBPELKQgWNtSeaA.png" /><figcaption>Fields in loans repayment data</figcaption></figure><p>4. Loan_defaulters — Contains data on all the members that defaulted their loan installments or did not pay on time. Contains the following fields with primary key as member_id:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGeQS8FPBWJNxqH-iYRDbw.png" /><figcaption>Fields in loans defaulters data</figcaption></figure><p>The 4 files created from one raw file are stored as CSV files in HDFS using Pyspark DataWriter API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*eFdRdWdXbbCsY8wglETIhQ.png" /><figcaption>raw files hierarchy in HDFS folder</figcaption></figure><blockquote>3. Perform data cleaning and pre-processing using finance/banking domain knowledge</blockquote><ol><li><strong>Cleaning Customers Data </strong>— Few cleanup tasks should be performed for every file irrespective of its nature and domain like :-</li></ol><ul><li><strong>Verifying data types of all columns</strong>. Avoid using “InferSchema” option while loading a file via DataFrame Reader API since it causes additional overhead to Spark executors of scanning the file twice — once for loading the entire dataset to Spark executor memory, second for loading subset of data for schema inference. This increases I/O cost and may also lead to wrongly inferred data type as Spark treats a field with mixed data types as string-type field<br>We can create our own schema that we need for a dataframe and pass it as a parameter to dataframe ReaderAPI function:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*8XQgHVA8DpX2rwsljUUhCQ.png" /><figcaption>wrongly inferred data type of column “annual_inc” as string with “inferSchema” option enabled</figcaption></figure><p>Hence we create a variable customer_schema where we explicitly imply data type for column “annual_inc” as float</p><pre> <br>customer_schema = &#39;member_id string, emp_title string, emp_length string,<br> home_ownership string, annual_inc float, addr_state string, zip_code string,<br> country string, grade string, sub_grade string, verification_status string,<br> tot_hi_cred_lim float, application_type string, annual_inc_joint float,<br> verification_status_joint string&#39;<br><br>customers_df=spark.read.format(&quot;csv&quot;).option(&quot;header&quot;,&quot;true&quot;).schema(customer_schema).load(&quot;&lt;path to customers.csv file&gt;&quot;)</pre><ul><li><strong>Renaming column names to self-explanatory forms</strong> — For customers_data, we can re-name few columns to more meaningful names like :<br>annual_inc — annual_income<br>tot_hi_cred_lim — total_high_credit_limit<br>zip_code — address_zipcode</li></ul><pre>“.withColumnRenamed(&quot;annual_inc&quot;, &quot;annual_income&quot;) \<br> .withColumnRenamed(&quot;addr_state&quot;, &quot;address_state&quot;) \<br> .withColumnRenamed(&quot;zip_code&quot;, &quot;address_zipcode&quot;) </pre><ul><li><strong>Adding Ingestion_date column</strong> — adding a column that indicates the date-time at which a particular record was ingested is helpful for log analysis, debugging and incremental loading.</li></ul><pre> from pyspark.sql.functions import current_timestamp<br>customers_df.withColumnRenamed(&quot;ingest_date&quot;,current_timestamp())</pre><ul><li><strong>Remove duplicate rows</strong> — To check if duplicate rows are present in a dataframe or a spark table, we run 2 functions:<br>1. df.count() <br>2. df.distinct().count()</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*ExiBsrQb0ZZ3tT6h8zXoWQ.png" /></figure><p>Since df.distinct().count() is lesser than df.count(), then it indicates presence of duplicate rows. Thus, we use <strong>distinct() </strong>or <strong>dropDuplicates() </strong>to remove duplicate rows from a dataframe</p><pre>customers_df = df.distinct()</pre><ul><li><strong>Removing nulls from “annual_income” column </strong>— This can be considered a feature engineering process to remove member_ids or rows that have null annual_income indicating that their annual_incomes are not correctly stated in the application or the member is a student. Since Lendingcart does not provide loans to students and cannot process loan applications of member ids with unknown incomes, they cannot be considered for loan applications(annual income is a critical attribute to calculate the loan score)</li><li><strong>Processing the “emp_length” column — </strong>Emp_length field, which indicates the employment length of the loan borrower, has the following values :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*6tObk8XzwABmR0HiX6xXPw.png" /></figure><p>We cannot perform mathematical operations on it unless we convert it to an integer-type column(the string “<strong>years</strong>” here would not help us in any kind of analysis and unnecessarily lengthens the memory space). Hence we convert it to an integer-type column by discarding all the non-numeric characters and replacing with empty strings and convert the column to integer</p><pre>from pyspark.sql.functions import regexp_replace,col<br>customers_df = df.withColumn(&quot;emp_length&quot;,regexp_replace(col(&quot;emp_length&quot;),&quot;(\D)&quot;,&quot;&quot;).cast(&quot;int&quot;))</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*SLkL0esbTzEpRIWa7412uQ.png" /></figure><p>We also replace nulls in “emp_length” column with the average employment_length value obtained from “emp_length” column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*ezO2SkHBHZWCXO2sTHuGJg.png" /><figcaption>nulls replaced with 6(average employment length of all the members)</figcaption></figure><ul><li><strong>Processing “address_state” field </strong>— The <em>address_state </em>field is required to have only state codes which should not exceed 2 characters. To ensure we have only 2 characters and if more than 2 characters are present then replace with “NA”, we execute the following Pyspark code</li></ul><pre>customers_df = customers_df.withColumn(&quot;address_state&quot;, when(length(col(&quot;address_state&quot;)) &gt; 2,<br> &quot;NA&quot;).otherwise(col(&quot;address_state&quot;)))”</pre><p>Finally, we save the processed customers_data back to HDFS path in Parquet format</p><pre>customers_data_cleaned.write.format(&quot;parquet&quot;).mode(&quot;overwrite&quot;)<br>.option(&quot;path&quot;,&lt;HDFS FOLDER PATH&gt;).save()</pre><p>You might find 200 parquet files created inside the specified folder since default number of shuffled partitions were 200. To check number of default partitions in your Spark Session use : <strong>spark.conf.get(“spark.sql.shuffle.partitions”)</strong></p><p>Here, Shuffling occured due to wide transformations like distinct and average taking place while cleaning customers_data</p><p>2. <strong>Loans Data Processing </strong>— I performed similar transformations and cleaning tasks like I did for Customers data like enforcing a schema, adding “ingestion_date” column, removing duplicate rows</p><ul><li>As a feature engineering task, it can be logical to say that loans data should have no null records in columns “loan_amount”, “funded_amnt”, “loan_term_months”, “interest_rate”, “monthly_installment”, “issue_date”, “loan_status” and “loan_purpose” because null values in either of these columns would indicate loan has not been initiated and hence is an invalid loan id. Thus, the below code removes records that have any null values in either of the columns mentioned in the python list</li></ul><pre>columns_to_check = [&quot;loan_amount&quot;, &quot;funded_amnt&quot;, &quot;loan_term_months&quot;,<br> &quot;interest_rate&quot;, &quot;monthly_installment&quot;, &quot;issue_date&quot;, &quot;loan_status&quot;,<br> &quot;loan_purpose&quot;]<br>loan_df_injested.na.drop(subset = columns_to_check)</pre><ul><li>“term” column in loans_data is crucial for calculating loan_score but currently is in string type form:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*hiigxuKKDBfo4felS3zb0Q.png" /></figure><p>We convert it to integer type by removing the “months” string and convert all the row values from months to years, finally re-naming it to “loan_term_years”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRT93iakykk0QGhQiwAGyw.png" /><figcaption>“term”column converted to integer type and renamed to “loan_term_years”</figcaption></figure><ul><li>“loan_purpose” column has multiple distinct values, most of which are large texts which are not useful for AI-ML team to determine loan application tag. Hence, we can clean it using generic practices. The raw dataset consists of following distinct values in “loan_purpose” column</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*kXvhM6sOPIcCME_oEhufQQ.png" /><figcaption>These are the top reasons given by the loan borrowers for their loan application.</figcaption></figure><p>Rest of the values that have just 1 distinct value in overall dataset look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbSurGxKrQmIrsWe5m9pGg.png" /></figure><p>These long texts would be occupying approximately 100 bytes of space per row, however, since it has no significance for our current objective, we can replace it with “others” which would take up merely 20 bytes of storage space per row eliminating huge storage costs. Hence, considering only top 20 reasons from the column, I created a python list hard-coding the values. Only row values that contain reasons from the list will remain the same, otherwise will be replaced with “others”</p><pre>loan_purpose_lookup = [&quot;debt_consolidation&quot;, &quot;credit_card&quot;,<br> &quot;home_improvement&quot;, &quot;other&quot;, &quot;major_purchase&quot;, &quot;medical&quot;, &quot;small_business&quot;,<br> &quot;car&quot;, &quot;vacation&quot;,<br> &quot;moving&quot;, &quot;house&quot;, &quot;wedding&quot;, &quot;renewable_energy&quot;,<br> &quot;educational&quot;]<br><br> loans_df = lonsdf.withColumn(&quot;loan_purpose&quot;,<br> when(col(&quot;loan_purpose&quot;).isin(loan_purpose_lookup),<br> col(&quot;loan_purpose&quot;)).otherwise(&quot;other&quot;))</pre><p>Finally, we save the processed, cleans loans data in parquet format under the same folder where customers data was saved</p><p>3. <strong>Processing Loans Repayment ane Defaulters table</strong></p><ul><li>General data cleaning tasks like schema enforcement while reading file, removal of duplicate rows, renaming columns, adding “ingest_date” field should be done like we did for the previous tables</li><li>For loan re-payments table, as the table describes attributes for loan repayments, we should drop rows if any nulls are found in columns — “total_principle_received”, “total_interest_received”, “total_late_fee_received”, “total_payment_received”, “last_payment_amount” (Similar logic that was applied in loans table cleaning). The above mentioned columns should not have nulls since they are strictly adhered to describing loan repayment quantitative values</li><li>For loan repayments, we have <em>total_payment_received </em>column which is the sum of columns <em>total_principle_received + total_interest_received + total_late_fee_received. </em>However, inexplicably, we have few records in <em>total_payment_received </em>column =0.0 while <em>total_principle_received </em>has a finite value. Hence, for <em>total_payment_received </em>column with 0.0, we calculate actual payment received by summing the necessary columns</li></ul><pre>loan_repayments = loan_repayments.withColumn(&quot;total_payment_received&quot;, when(<br> (col(&quot;total_payment_received&quot;) == 0.0) &amp; (col(&quot;total_principle_received&quot;) !=<br> 0.0),col(&quot;total_principle_received&quot;)+col(&quot;total_interest_received&quot;)+col(&quot;total_late_fee_received&quot;))</pre><p>Also, we have gotten rid of records where <em>total_payment_received=0.0 and total_principle_received = 0.0 </em>as these attribute values do not qualify under loan_repayments table</p><ul><li>In defaulters raw data, we have a column called <em>deling_2_yrs </em>which states the the number of times a member has missed paying the installment on due date in the last 2 years. This data has float values like 2.0, 3.0, 45.5( which doesn&#39;t make sense since a member cannot miss payment 45.5 times). It also has bad data in form of mixed data types and also nulls from upstream sources</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*Rhj5k0-MRqVa8JdWzVcuGg.png" /><figcaption>values from other columns entered in delinq_2yrs column</figcaption></figure><p>Hence, to harmonize this column, we must convert the field to integer data type. In this way, the string data type values in form of bad data will be converted to null and also float values like 45.5 will be rounded off to a valid “number of times” value. Subsequently, instances with nulls indicate that a member has never defaulted his installment. Hence, we can replace nulls with 0s</p><pre>defaulters_df = defaulters_df.withColumn(&quot;delinq_2yrs&quot;, col(&quot;delinq_2yrs&quot;).cast(&quot;integer&quot;)).fillna(0, subset =[&quot;delinq_2yrs&quot;])</pre><ul><li>For defaulters dataframe, from the previous cleaning step, we can now distinguish members who are defaulters and non-defaulters. I will divide the defaulters dataframe into 2 files :<br>1. <strong>delinquent_defaulters </strong>— This dataframe stores all attributes of delinquency of members who were defaulted their payments. Hence, it would contain columns : member_id, delinq_2yrs, delinq_amnt, mths_since_last_delinq. We can create this dataframe by eliminating members who are non-defaulters and have no delinquency records by applying filters to the column delinq_2yrs and mths_since_last_delinq. Non defaulters would have 0 number of times of delinquency since last 2 years or 0 number of months since their last delinquency:</li></ul><pre>defaulters_df.createOrReplaceTempView(&quot;loan_defaulter&quot;)<br>defaulters_delinquency_df = spark.sql(&quot;select member_id, delinq_2yrs, delinq_amnt,<br> int(mths_since_last_delinq) from loan_defaulter where delinq_2yrs&gt;0 or<br> mths_since_last_delinq&gt;0&quot;)</pre><p>2. <strong>public_rec_defaulters </strong>— In this dataset information about only those member_ids (borrowers) is considered for whom either there is public record or bankruptcy record. It contains following columns : member ids, pub_rec, pub_rec_bankruptcies and inq_last_6mths columns. Same processing steps have been applied to the selected columns as <em>delinq_2yrs </em>column in delinquent_defaulters file(converting to integer and filling nulls with zeros)</p><pre>defaulters_df.createOrReplaceTempView(&quot;loan_defaulter&quot;)<br>public_rec_defaulters_df = spark.sql(&quot;select member_id,pub_rec,pub_rec_bankruptcies,inq_last_6mths from loan_defaulter&quot;)</pre><p>We now have cleaned all the files that we had normalized and stored them in a folder on HDFS in parquet format.</p><p>Fewer teams of data analysts may require these cleaned files for analysis where they can use SQL queries to gather insights and understand data. In that case, one may convert these parquet files to external tables. For those who do not know what are external tables, they are spark tables where one can create schema on top of the underlying data where the schema would be stored in Hive metastore but the underlying data will be external to Hive metastore and would be stored in its original location(in our case, HDFS). Hence, analysts would be able to run SQL queries on this spark external table in Hive</p><p>Hence, data cannot be deleted by anyone who do not have “Execute” permissions in the external folder. If “drop table” query is ran, only schema is dropped and can no longer be accessed as a hive table while the data still remains in the external location.</p><p>Other teams may also require a consolidated view of all the cleaned tables as one single table. In this case, we can join all 5 external tables in Hive as one de-normalized table and store it as a view in Hive Metastore.</p><pre>create or replace view &lt;database where you want to store the view&gt;.&lt;view name&gt; as<br>select * from customers c left join loans l on c.member_id=l.member_id<br>left join loan_repayments r on l.loan_id=r.loan_id<br>left join loan_defaulters_delinq d on c.member_id=d.member_id<br>left join loan_public_rec_defaulters e on c.member_id=e.member_id</pre><p><em>In the above query, I used * to select all columns, however, in industry, please stipulate all columns explicitly as “star select” is not a good practice in Production </em>😉</p><p>Suppose if these 5 cleaned tables are refreshed or updated every 24 hours. From the above query, we have created a view definition and stored it in Hive Metastore. Hence, teams can get a consolidated view of all 5 tables using this view which would not be older than 24 hours. Hence, they get access to up-to-date data. However, everytime the concerned team runs the view using “<em>select * from view</em>” , Hive will run the create table query and derive the results at a slow pace as these results are not stored anywhere physically.</p><p>Alternatively, if a team wants a faster access to the consolidated table, we can create a scheduled job where the join query is ran and stored in a managed table in Hive. Managed tables are tables where data and schema are both stored in Hive ( schema in Hive metastore and underlying data in warehouse). However, this scheduled job would be computationally expensive to run daily every 24 hours. Hence, this job would be pre-set to run one weekly. Hence, teams would now get faster access to this managed table but it would not be the latest data (since cleaned tables are refreshed every 24 hours)</p><p>Hence, a trade-off occurs in creating view and a managed table for consolidated access to one big table. If faster access is required, we create a managed table but compromise on data recency will prevail. If up-to-date data is required, we may create views but slow access will occur</p><blockquote>4. Identifying and reporting bad data</blockquote><ul><li>Among cleaned files, customers, delinquent_defaulters and pub_rec_defaulters tables had member_ids as primary keys. But upon investigating, we found out that there were duplicate member_ids in all 3 tables.<br>For eg: In customers table, there were 5 records with a repeating member_id who had different credit_limit values in the <em>high_credit_limit </em>field. Similarly in delinquent_defaulters, we have different values in <em>delinq_2_yrs </em>field for the same member_id. <br>These member_ids have ambiguous attributes and we cannot be making assumptions as to what would be the recent attribute of the concerned member_id. Hence, these member ids need to be reported to the Upstream team who are the data creators of the raw data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7JqD_3Uew-Btpi898418A.png" /><figcaption>same member ids with different credit limits</figcaption></figure><ul><li>Hence, I created 3 dataframes from these 3 tables consisting of only member_ids that have repetitive records terming them as bad data.</li></ul><pre>customers_df = spark.sql(&quot;&quot;&quot;SELECT member_id from (select member_id, count(*) as total from customers<br>group by member_id having total &gt; 1)&quot;&quot;&quot;)</pre><ul><li>To create a consolidated dataframe of member_ids that need to be reported to the Upstream team, we can run union function on the 3 dataframes with bad data and store the final dataframe with unique and problematic member_ids on HDFS</li></ul><pre>bad_member_ids_df = customer_df.select(&quot;member_id&quot;). \<br>                unionByName(delinquent_defaulters_df.select(&quot;member_id&quot;)). \<br>                unionByName(pub_rec_defaulters_df.select(&quot;member_id&quot;))<br><br>final_bad_df = bad_member_ids_df.distinct()</pre><ul><li>We can now use the above dataframe <em>final_bad_df </em>to remove the problematic member_ids from the original cleaned tables using spark SQL . Thus, now we have unique member_ids throughout all the 3 tables and can be used as a primary key</li></ul><pre>final_bad_df.createOrReplaceTempView(&quot;duplicate_members&quot;)<br>customers_cleaned_new = spark.sql (&quot;&quot;&quot;select * from customers where member_id<br>not in (select member_id from duplicate_members)&quot;&quot;&quot;)</pre><blockquote><em>4. Perform data processing</em></blockquote><p>After cleaning the raw file and normalizing it into 5 separate clean files, we can now use these files to calculate loan_score KPI which will determine the rejection/approval rate of a loan application. Loan score calculation depends on the following parameters:</p><ul><li>Loan Payment History describing how diligently the loan was paid on time (info retained from loan_repayments table and loans table) :<br>If <em>last_payment </em>field &lt; <em>installment </em>field, score decreases, If <em>last_payment </em>field ≥ <em>installment </em>field, score increases. If <em>total_payment_received </em>field value is close to the <em>total_principal_amount </em>field, this indicates loan borrower is more likely to pay off the whole loan amount, hence score would increase and vice versa</li><li>Customer’s Financial Health like his salary, whether he owns a house, his profession, etc ( can be obtained from customers data and loans table):<br>Owning a home will increase the loan score. If <em>credit_limit_amount </em>field &lt; <em>funded_amount</em>, loan score increases, otherwise if <em>credit_limit_amount </em>field = <em>funded_amount</em>, loan score may decrease as it indicates that loan borrower wants to exhaust all of the amount available in his credit limit and has less financial stability. Moreover if <em>loan_status </em>field is marked as “ fully paid”, loan score increases and vice versa. Also, scores are calculated on the basis of grades and sub-grades assigned by the institutions to each member</li><li>Loan defaulters history ( can be obtained from delinquency and public records table)<br>Greater the values in <em>delinq_2yrs</em>, <em>pub_rec</em>, <em>pub_rec_bankruptcies</em>, <em>inq_last_6mths </em>field records for a loan borrower, lower the loan score and vice versa</li></ul><p>Hence, the above components have the following weightage in calculating the final score :<br>1. payment_history = 20%<br>2. loan_default_history = 45%<br>3. financial health = 35%</p><p>I have configured some variables to some values using “<em>spark.conf.set</em>” so it becomes easy to modify these variables</p><pre>spark.conf.set(&quot;spark.sql.unacceptable_rated_pts&quot;, 0)<br>spark.conf.set(&quot;spark.sql.very_bad_rated_pts&quot;, 100)<br>spark.conf.set(&quot;spark.sql.bad_rated_pts&quot;, 250)<br>spark.conf.set(&quot;spark.sql.good_rated_pts&quot;, 500)<br>spark.conf.set(&quot;spark.sql.very_good_rated_pts&quot;, 650)<br>spark.conf.set(&quot;spark.sql.excellent_rated_pts&quot;, 800)<br><br>spark.conf.set(&quot;spark.sql.unacceptable_grade_pts&quot;, 750)<br>spark.conf.set(&quot;spark.sql.very_bad_grade_pts&quot;, 1000)<br>spark.conf.set(&quot;spark.sql.bad_grade_pts&quot;, 1500)<br>spark.conf.set(&quot;spark.sql.good_grade_pts&quot;, 2000)<br>spark.conf.set(&quot;spark.sql.very_good_grade_pts&quot;, 2500)<br></pre><p><strong><em>Creating last_payment_pts and total_payment_pts column based on Loan repayment history<br></em></strong>The <strong><em>last_payment_pts</em></strong> column is created to calculate points based on <em>last_payment_amount </em>column and <em>monthly_installment </em>column. Points would be allocated to member_id on the following conditions:</p><ul><li>if <em>last_payment_amount &lt; monthly_installment*0.5 — very_bad_rated_points</em></li><li>if <em>last_payment_amount ≥ monthly_installment*0.5 and last_payment_amount &lt; monthly_installment — bad_rated_points</em></li><li>if <em>last_payment_amount =monthly_installment— good_rated_points</em></li><li>if <em>last_payment_amount &gt;monthly_installment and last_payment_amount &lt; monthly_installment*1.5 — very_good_rated_points</em></li><li>if <em>last_payment_amount &gt;monthly_installment *1.5— excellent_rated_points</em></li><li><em>If the</em> <em>last_payment_amount and monthly_installment values dont fit in any of the above criterias — unacceptable_rated_points</em></li></ul><p>The <strong><em>total_payment_pts </em></strong>column is created to calculate points based on <em>total_payment_received </em>column and <em>funded_amount </em>column. Points would be allocated to member_id on the following conditions:</p><ul><li>if <em>total_payment_received≥funded_amount * 0.5 — very_good_rated_points</em></li><li>if <em>total_payment_received&lt;funded_amount * 0.5 and total_payment_received&gt;0— good_rated_points</em></li><li>if <em>total_payment_received=0 or total_payment_received is null— unacceptable_rated_points</em></li></ul><p>Make sure to remove member_ids that are problematic which I have done at the end of the spark SQL query</p><pre>df1 = spark.sql(&quot;select c.member_id, \<br>   case \<br>   when p.last_payment_amount &lt; (c.monthly_installment * 0.5) then ${spark.sql.very_bad_rated_pts} \<br>   when p.last_payment_amount &gt;= (c.monthly_installment * 0.5) and p.last_payment_amount &lt; c.monthly_installment then ${spark.sql.very_bad_rated_pts} \<br>   when (p.last_payment_amount = (c.monthly_installment)) then ${spark.sql.good_rated_pts} \<br>   when p.last_payment_amount &gt; (c.monthly_installment) and p.last_payment_amount &lt;= (c.monthly_installment * 1.50) then ${spark.sql.very_good_rated_pts} \<br>   when p.last_payment_amount &gt; (c.monthly_installment * 1.50) then ${spark.sql.excellent_rated_pts} \<br>   else ${spark.sql.unacceptable_rated_pts} \<br>   end as last_payment_pts, \<br>   case \<br>   when p.total_payment_received &gt;= (c.funded_amount * 0.50) then ${spark.sql.very_good_rated_pts} \<br>   when p.total_payment_received &lt; (c.funded_amount * 0.50) and p.total_payment_received &gt; 0 then ${spark.sql.good_rated_pts} \<br>   when p.total_payment_received = 0 or (p.total_payment_received) is null then ${spark.sql.unacceptable_rated_pts} \<br>   end as total_payment_pts \<br>from lending_club.loans_repayments p \<br>inner join lending_club.loans c on c.loan_id = p.loan_id where member_id NOT IN (select member_id from bad_data_customer)&quot;)<br><br>df1.createOrReplaceTempView(&quot;payment_history_tbl&quot;)</pre><p><strong><em>Creating delinq_points, public_rec_points, public_bankrupties_pts and enquiry_pts column based on Loan defaulters history</em></strong></p><ul><li>The <strong><em>delinq_points </em></strong>column is created to calculate points based on <em>delinq_2yrs </em>column</li><li>The <strong><em>public_rec_points </em></strong>column is created to calculate points based on <strong><em>pub_rec </em></strong>column</li><li>The <strong><em>public_bankrupties_pts </em></strong>column is created to calculate points based on <strong><em>pub_rec_bankruptcies </em></strong>column</li><li>The <strong><em>enquiry_pts </em></strong>column is created to calculate points based on <strong><em>inq_last_6mnths </em></strong>column</li></ul><pre>df2 = park.sql(<br>    &quot;select p.*, \<br>    CASE \<br>    WHEN d.delinq_2yrs = 0 THEN ${spark.sql.excellent_rated_pts} \<br>    WHEN d.delinq_2yrs BETWEEN 1 AND 2 THEN ${spark.sql.bad_rated_pts} \<br>    WHEN d.delinq_2yrs BETWEEN 3 AND 5 THEN ${spark.sql.very_bad_rated_pts} \<br>    WHEN d.delinq_2yrs &gt; 5 OR d.delinq_2yrs IS NULL THEN ${spark.sql.unacceptable_grade_pts} \<br>    END AS delinq_pts, \<br>    CASE \<br>    WHEN l.pub_rec = 0 THEN ${spark.sql.excellent_rated_pts} \<br>    WHEN l.pub_rec BETWEEN 1 AND 2 THEN ${spark.sql.bad_rated_pts} \<br>    WHEN l.pub_rec BETWEEN 3 AND 5 THEN ${spark.sql.very_bad_rated_pts} \<br>    WHEN l.pub_rec &gt; 5 OR l.pub_rec IS NULL THEN ${spark.sql.very_bad_rated_pts} \<br>    END AS public_records_pts, \<br>    CASE \<br>    WHEN l.pub_rec_bankruptcies = 0 THEN ${spark.sql.excellent_rated_pts} \<br>    WHEN l.pub_rec_bankruptcies BETWEEN 1 AND 2 THEN ${spark.sql.bad_rated_pts} \<br>    WHEN l.pub_rec_bankruptcies BETWEEN 3 AND 5 THEN ${spark.sql.very_bad_rated_pts} \<br>    WHEN l.pub_rec_bankruptcies &gt; 5 OR l.pub_rec_bankruptcies IS NULL THEN ${spark.sql.very_bad_rated_pts} \<br>    END as public_bankruptcies_pts, \<br>    CASE \<br>    WHEN l.inq_last_6mths = 0 THEN ${spark.sql.excellent_rated_pts} \<br>    WHEN l.inq_last_6mths BETWEEN 1 AND 2 THEN ${spark.sql.bad_rated_pts} \<br>    WHEN l.inq_last_6mths BETWEEN 3 AND 5 THEN ${spark.sql.very_bad_rated_pts} \<br>    WHEN l.inq_last_6mths &gt; 5 OR l.inq_last_6mths IS NULL THEN ${spark.sql.unacceptable_rated_pts} \<br>    END AS enq_pts \<br>    FROM lending_club.loans_defaulters_detail_rec_enq_new l \<br>    INNER JOIN lending_club.loans_defaulters_delinq_new d ON d.member_id = l.member_id  \<br>    INNER JOIN payment_history_tbl p ON p.member_id = l.member_id where l.member_id NOT IN (select member_id from bad_data_customer)&quot;)<br><br>df2.createOrReplaceTempView(&quot;defaulters_payment_history_tbl&quot;)</pre><p><strong><em>Creating loan_status_points, credit_limit_points, home_pts and grade_pts column based on Financial health of loan borrower</em></strong></p><ul><li>The <strong><em>loan_status_points </em></strong>column is created to calculate points based on <em>loan_status </em>column</li><li>The <strong><em>credit_limit_points </em></strong>column is created to calculate points based on <em>funded_amount and total_high_credit_limit </em>column</li><li>The <strong><em>home_pts </em></strong>column is created to calculate points based on <em>home_ownership </em>column</li><li>The <strong><em>grade_pts </em></strong>column is created to calculate points based on <em>garde and sub_grade </em>column</li></ul><pre>final_df = spark.sql(&quot;select ldef.*, \<br>   CASE \<br>   WHEN LOWER(l.loan_status) LIKE &#39;%fully paid%&#39; THEN ${spark.sql.excellent_rated_pts} \<br>   WHEN LOWER(l.loan_status) LIKE &#39;%current%&#39; THEN ${spark.sql.good_rated_pts} \<br>   WHEN LOWER(l.loan_status) LIKE &#39;%in grace period%&#39; THEN ${spark.sql.bad_rated_pts} \<br>   WHEN LOWER(l.loan_status) LIKE &#39;%late (16-30 days)%&#39; OR LOWER(l.loan_status) LIKE &#39;%late (31-120 days)%&#39; THEN ${spark.sql.very_bad_rated_pts} \<br>   WHEN LOWER(l.loan_status) LIKE &#39;%charged off%&#39; THEN ${spark.sql.unacceptable_rated_pts} \<br>   else ${spark.sql.unacceptable_rated_pts} \<br>   END AS loan_status_pts, \<br>   CASE \<br>   WHEN LOWER(a.home_ownership) LIKE &#39;%own&#39; THEN ${spark.sql.excellent_rated_pts} \<br>   WHEN LOWER(a.home_ownership) LIKE &#39;%rent&#39; THEN ${spark.sql.good_rated_pts} \<br>   WHEN LOWER(a.home_ownership) LIKE &#39;%mortgage&#39; THEN ${spark.sql.bad_rated_pts} \<br>   WHEN LOWER(a.home_ownership) LIKE &#39;%any&#39; OR LOWER(a.home_ownership) IS NULL THEN ${spark.sql.very_bad_rated_pts} \<br>   END AS home_pts, \<br>   CASE \<br>   WHEN l.funded_amount &lt;= (a.total_high_credit_limit * 0.10) THEN ${spark.sql.excellent_rated_pts} \<br>   WHEN l.funded_amount &gt; (a.total_high_credit_limit * 0.10) AND l.funded_amount &lt;= (a.total_high_credit_limit * 0.20) THEN ${spark.sql.very_good_rated_pts} \<br>   WHEN l.funded_amount &gt; (a.total_high_credit_limit * 0.20) AND l.funded_amount &lt;= (a.total_high_credit_limit * 0.30) THEN ${spark.sql.good_rated_pts} \<br>   WHEN l.funded_amount &gt; (a.total_high_credit_limit * 0.30) AND l.funded_amount &lt;= (a.total_high_credit_limit * 0.50) THEN ${spark.sql.bad_rated_pts} \<br>   WHEN l.funded_amount &gt; (a.total_high_credit_limit * 0.50) AND l.funded_amount &lt;= (a.total_high_credit_limit * 0.70) THEN ${spark.sql.very_bad_rated_pts} \<br>   WHEN l.funded_amount &gt; (a.total_high_credit_limit * 0.70) THEN ${spark.sql.unacceptable_rated_pts} \<br>   else ${spark.sql.unacceptable_rated_pts} \<br>   END AS credit_limit_pts, \<br>   CASE \<br>   WHEN (a.grade) = &#39;A&#39; and (a.sub_grade)=&#39;A1&#39; THEN ${spark.sql.excellent_rated_pts} \<br>   WHEN (a.grade) = &#39;A&#39; and (a.sub_grade)=&#39;A2&#39; THEN (${spark.sql.excellent_rated_pts} * 0.95) \<br>   WHEN (a.grade) = &#39;A&#39; and (a.sub_grade)=&#39;A3&#39; THEN (${spark.sql.excellent_rated_pts} * 0.90) \<br>   WHEN (a.grade) = &#39;A&#39; and (a.sub_grade)=&#39;A4&#39; THEN (${spark.sql.excellent_rated_pts} * 0.85) \<br>   WHEN (a.grade) = &#39;A&#39; and (a.sub_grade)=&#39;A5&#39; THEN (${spark.sql.excellent_rated_pts} * 0.80) \<br>   WHEN (a.grade) = &#39;B&#39; and (a.sub_grade)=&#39;B1&#39; THEN (${spark.sql.very_good_rated_pts}) \<br>   WHEN (a.grade) = &#39;B&#39; and (a.sub_grade)=&#39;B2&#39; THEN (${spark.sql.very_good_rated_pts} * 0.95) \<br>   WHEN (a.grade) = &#39;B&#39; and (a.sub_grade)=&#39;B3&#39; THEN (${spark.sql.very_good_rated_pts} * 0.90) \<br>   WHEN (a.grade) = &#39;B&#39; and (a.sub_grade)=&#39;B4&#39; THEN (${spark.sql.very_good_rated_pts} * 0.85) \<br>   WHEN (a.grade) = &#39;B&#39; and (a.sub_grade)=&#39;B5&#39; THEN (${spark.sql.very_good_rated_pts} * 0.80) \<br>   WHEN (a.grade) = &#39;C&#39; and (a.sub_grade)=&#39;C1&#39; THEN (${spark.sql.good_rated_pts}) \<br>   WHEN (a.grade) = &#39;C&#39; and (a.sub_grade)=&#39;C2&#39; THEN (${spark.sql.good_rated_pts} * 0.95) \<br>   WHEN (a.grade) = &#39;C&#39; and (a.sub_grade)=&#39;C3&#39; THEN (${spark.sql.good_rated_pts} * 0.90) \<br>   WHEN (a.grade) = &#39;C&#39; and (a.sub_grade)=&#39;C4&#39; THEN (${spark.sql.good_rated_pts} * 0.85) \<br>   WHEN (a.grade) = &#39;C&#39; and (a.sub_grade)=&#39;C5&#39; THEN (${spark.sql.good_rated_pts} * 0.80) \<br>   WHEN (a.grade) = &#39;D&#39; and (a.sub_grade)=&#39;D1&#39; THEN (${spark.sql.bad_rated_pts}) \<br>   WHEN (a.grade) = &#39;D&#39; and (a.sub_grade)=&#39;D2&#39; THEN (${spark.sql.bad_rated_pts} * 0.95) \<br>   WHEN (a.grade) = &#39;D&#39; and (a.sub_grade)=&#39;D3&#39; THEN (${spark.sql.bad_rated_pts} * 0.90) \<br>   WHEN (a.grade) = &#39;D&#39; and (a.sub_grade)=&#39;D4&#39; THEN (${spark.sql.bad_rated_pts} * 0.85) \<br>   WHEN (a.grade) = &#39;D&#39; and (a.sub_grade)=&#39;D5&#39; THEN (${spark.sql.bad_rated_pts} * 0.80) \<br>   WHEN (a.grade) = &#39;E&#39; and (a.sub_grade)=&#39;E1&#39; THEN (${spark.sql.very_bad_rated_pts}) \<br>   WHEN (a.grade) = &#39;E&#39; and (a.sub_grade)=&#39;E2&#39; THEN (${spark.sql.very_bad_rated_pts} * 0.95) \<br>   WHEN (a.grade) = &#39;E&#39; and (a.sub_grade)=&#39;E3&#39; THEN (${spark.sql.very_bad_rated_pts} * 0.90) \<br>   WHEN (a.grade) = &#39;E&#39; and (a.sub_grade)=&#39;E4&#39; THEN (${spark.sql.very_bad_rated_pts} * 0.85) \<br>   WHEN (a.grade) = &#39;E&#39; and (a.sub_grade)=&#39;E5&#39; THEN (${spark.sql.very_bad_rated_pts} * 0.80) \<br>   WHEN (a.grade) in (&#39;F&#39;, &#39;G&#39;) THEN (${spark.sql.unacceptable_rated_pts}) \<br>   END AS grade_pts \<br>   FROM defaulters_payment_history_tbl ldef \<br>   INNER JOIN lending_club.loans l ON ldef.member_id = l.member_id \<br>   INNER JOIN lending_club.customers_new a ON a.member_id = ldef.member_id where ldef.member_id NOT IN (select member_id from bad_data_customer)&quot;) <br><br>final_df.createOrReplaceTempView(&quot;final_points_tbl&quot;)</pre><ul><li>From the above query, you can see that I have then performed an inner join of all 3 tables created on joining key as member_id to only retain members who have all attributes. Hence, in this final table, we will have a consolidated view of all points calculated on all the criterias:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmEEXCnIxpB58ao78XdtYQ.png" /><figcaption>final joined table containing points calculated for each member from each factor</figcaption></figure><ul><li>Using the points from the above table, we calculate final score of each criteria for each member_id based on the weightage rules set for each criteria: <br>1.payment_history = 20%<br>2. loan_default_history = 45%<br>3. financial health = 35%</li><li>Then we calculate the final loan score by adding the weighted scores from each criteria</li></ul><pre>loan_score = spark.sql(&quot;SELECT member_id, \<br>((last_payment_pts+total_payment_pts)*0.20) as payment_history_pts, \<br>((delinq_pts + public_records_pts + public_bankruptcies_pts + enq_pts) * 0.45) as defaulters_history_pts, \<br>((loan_status_pts + home_pts + credit_limit_pts + grade_pts)*0.35) as financial_health_pts \<br>FROM final_points_tbl&quot;)<br><br>final_loan_score = loan_score.withColumn(&#39;loan_score&#39;, loan_score.payment_history_pts + loan_score.defaulters_history_pts + loan_score.financial_health_pts)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*_tiqxaZk0InUS7eLlnrmbQ.png" /><figcaption>Final table with weighted points and final loan_score</figcaption></figure><ul><li>At last, we will assign grade on the basis of points earned by each member_id to determine the rate of risk involved in giving loan. I have assigned grades based on the points assigned in “spark.conf.set” code block</li></ul><pre>final_loan_score.createOrReplaceTempView(&quot;loan_score_eval&quot;)<br><br>loan_score_final = spark.sql(&quot;select ls.*, \<br>case \<br>WHEN loan_score &gt; ${spark.sql.very_good_grade_pts} THEN &#39;A&#39; \<br>WHEN loan_score &lt;= ${spark.sql.very_good_grade_pts} AND loan_score &gt; ${spark.sql.good_grade_pts} THEN &#39;B&#39; \<br>WHEN loan_score &lt;= ${spark.sql.good_grade_pts} AND loan_score &gt; ${spark.sql.bad_grade_pts} THEN &#39;C&#39; \<br>WHEN loan_score &lt;= ${spark.sql.bad_grade_pts} AND loan_score  &gt; ${spark.sql.very_bad_grade_pts} THEN &#39;D&#39; \<br>WHEN loan_score &lt;= ${spark.sql.very_bad_grade_pts} AND loan_score &gt; ${spark.sql.unacceptable_grade_pts} THEN &#39;E&#39;  \<br>WHEN loan_score &lt;= ${spark.sql.unacceptable_grade_pts} THEN &#39;F&#39; \<br>end as loan_final_grade \<br>from loan_score_eval ls&quot;)</pre><ul><li>Thus, this final dataframe can now be stored in a processed folder in HDFS which can be used seamlessly by AI-ML team, data analysts and any other team that wants to analyse loan borrower credibility. Even the datasets raw folder or cleaned folder can be used by a team of Power BI developers to further develop dashboards depicting customer repayment history patterns, graphing out customer financial health and so on….</li></ul><p>In the end, client is king. The domain knowledge applied in the E2E data transformation journey needs to be brainstormed with the client in order to meet business requirements and produce outputs that reflect the company”s strategy ourcomes</p><p><em>Thankyou for taking out time for reading my article ! Please do provide feedbacks as to how the article can be further improved or any errors if you find one </em>😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5352621c10f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>