31. Amounts that arrive as text

PySparkEasySchema trap

data cleaning · casting · try_cast · regexp_replace · data types

Open in Colab
How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

A partner sends payments in a spreadsheet export. The amount column was typed by people, so it is text: sometimes with a rupee sign, sometimes with thousands separators, sometimes "N/A".

The load job casts the column to a decimal. In the old cluster the bad values quietly became NULL and nobody knew how many there were. After the upgrade to Spark 4 the job does not finish at all: one bad value stops it.

Input tables

raw_payments

One row per payment.

Column Type Description
payment_id BIGINT Unique per payment.
amount_text STRING The amount as it was typed. Can be NULL or empty.

Look at the variety first: raw_payments.select("amount_text").distinct().show(200, truncate=False).

Requirement

Return every payment with its amount as a number.

To read an amount:

  1. Remove the rupee markers ₹, Rs., Rs and INR, and every comma. Commas are thousands separators, in western (1,234,567) or Indian (12,34,567) grouping.
  2. Remove spaces at the start and the end.
  3. If what is left is a plain number, such as 1299, 1299.50 or -200.00, that is the amount. A minus sign means a refund and is valid. So is 0.
  4. Anything else is not an amount: N/A, an empty value, 12.5.3, 1299.00 USD.

  5. amount is the number, and NULL when the text is not an amount.

  6. is_valid is true when amount is not NULL and false otherwise.
  7. Every payment appears, valid or not. The job must not fail on bad values.

Expected output

One row per payment.

Column Type Description
payment_id BIGINT
amount DECIMAL(12,2) NULL if the text is not an amount.
is_valid BOOLEAN

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

Three steps, in this order:

  1. Clean what you understand. Remove the things you know are decoration: the rupee markers and the thousands separators.
  2. Convert with try_cast. It returns NULL for text that is not a number, instead of stopping the job.
  3. Keep the evidence. A separate is_valid column says which rows could not be read, so they can be counted, reported and fixed at the source.
cleaned = F.trim(F.regexp_replace("amount_text", r"₹|Rs\.?|INR|,", ""))
amount = cleaned.try_cast("decimal(12,2)")

The pattern is a list of alternatives: ₹, or Rs with an optional dot, or INR, or a comma. It removes only those. Anything else that is not a number stays in the text, and try_cast then rejects it. That is the point: the cleaning is narrow, so that surprises still show up as invalid rows.

The target type is DECIMAL, not DOUBLE. Money needs exact decimal arithmetic.

Of the 126 payments, 113 are valid amounts and 13 are not. 9 of the valid ones are refunds with a minus sign.

What the cast does in each Spark version

Spark 4, plain cast. The job stops at the first value it cannot read:

[CAST_INVALID_INPUT] The value '₹69,522.50' of the type "STRING" cannot be cast
to "DECIMAL(12,2)" because it is malformed. ... Use `try_cast` to tolerate
malformed input and return NULL instead.

Cleaning first does not make the plain cast safe. After cleaning, the job stops on the empty string instead.

Spark 3, or ANSI mode switched off. The same cast returns NULL for every value it cannot read, and says nothing. On this data that is 65 valid amounts turned into NULL along with the 13 bad ones. This is the old behaviour from the story.

try_cast gives the quiet behaviour on purpose, one expression at a time. That is fine as long as you then count the NULLs, which is what is_valid is for.

Common wrong answers

try_cast without cleaning. No error, and 65 good amounts are lost: everything with a rupee marker or a comma.

Removing only the commas. 57 amounts are still lost: the ones with ₹, Rs or INR.

Rs without the optional dot. Rs. 300.50 becomes . 300.50, which is not a number. 9 amounts lost. In a regular expression a dot means "any character", so the literal dot is written \., and ? makes it optional.

Keeping only digits and dots: regexp_replace(amount_text, "[^0-9.]", ""). The popular one-liner, and the most dangerous answer here, because it produces numbers.

  • The minus sign is removed. All 9 refunds become payments.
  • 1299.00 USD becomes 1299.00. It was a dollar amount.
  • 1 299 becomes 1299.00. Nobody knows what was meant.
  • Rs. 300.50 becomes .300.50, which is not a number, so 9 good amounts are lost as well.

20 rows are wrong, and the total goes from 71,545,404.44 to 80,396,910.52. Nothing fails. A cleaning rule that deletes everything it does not recognise cannot tell you that it met something it did not recognise.

Keeping digits, dots and the minus sign. The refunds survive, the other problems remain. 11 rows wrong.

try_cast("double"). The type is wrong, and binary floating point cannot hold most decimal fractions exactly. Totals of doubles drift by fractions of a paisa.

decimal(12,0). The paise are rounded away. 69 amounts wrong.

is_valid from the text: amount_text.isNotNull(). N/A is not NULL. 12 rows are flagged valid with no amount.

Replacing invalid amounts with 0. A payment of unknown size is not a payment of zero. Sums still look fine and averages are pulled down.

Dropping the invalid rows. 113 rows instead of 126. The 13 payments happened; somebody has to chase them.

Two things try_cast does that you might not expect

  • It ignores spaces around the number. ' 450 ' converts without trim. The reference solution trims anyway, so the rule is visible in the code.
  • It accepts scientific notation. '1e3' converts to 1000.00. If a product code like 1E3 can end up in this column, check the format with a regular expression before casting.

Edge cases in the data

Kind of value Expected What it catches
₹1,299.00, Rs. 300.50, Rs 12,34,567.50, INR 2500.00 valid Casting without cleaning.
12,34,567.50 valid Indian digit grouping: commas are not every three digits.
-200.00 valid, negative Stripping everything that is not a digit.
0, 0.00 valid, zero Treating 0 as "missing".
₹ 450.5 450.50 One decimal place is still a number.
1299.00 USD, 1 299 invalid Stripping everything that is not a digit.
12.5.3, --, abc, twelve hundred invalid A plain cast.
₹, Rs. invalid A marker with nothing behind it cleans to an empty string.
N/A, NULL (as text), empty, spaces, a real NULL invalid is_valid taken from the text.