Aller au contenu

Leçon 12 · Types, Text and Dates

Converting Data Types Safely

Convert messy text into numbers, money, percentages and booleans with explicit rules, handle locale formats and report every value that fails to convert.

Files often deliver everything as text. To calculate, sort or compare correctly, each column needs the right type. As text, "100" sorts before "9", and adding two strings glues them together. Conversion is a common place for silent data loss, so make failures visible.

Decide the type per column

Content Suitable type
Quantities and counts Integer
Measurements Floating point
Money Decimal, or integer minor units such as cents
Yes/no Boolean, plus missing
IDs and codes Text
Dates and times Date or datetime types
Short fixed lists Category

Why not floating point for money? Binary floating point cannot represent most decimal fractions exactly.

Python Floats versus Decimal

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Build Decimal values from strings. Building one from a float carries the float's error with it.

Parse numbers with a known format

1,234 is one thousand two hundred thirty-four in some places and about one and a quarter in others. A parser cannot know which unless you tell it. Set the decimal and thousands separators per source.

Python Parse numbers and report failures

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The parser rejects 1,23 because the grouping is wrong for this format. Simply deleting commas would have turned it into 123. Showing negative numbers in parentheses is an accounting convention. Use that rule only if your source follows it.

Units, symbols and percentages

Remove a currency symbol only after you record the currency. $ is used by several currencies. Store amount and currency in separate columns, and never add different currencies without a stated exchange rate and date. For percentages, decide whether 12% becomes 0.12 or 12, and name the column to match, such as discount_fraction or discount_pct.

Booleans

In Python, any non-empty string counts as true, so bool("False") is True. Map the allowed words explicitly.

Python Map booleans explicitly

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep "no" and "unknown" apart. They mean different things.

pandas: coerce, then inspect

pd.to_numeric(..., errors="coerce") turns bad values into missing ones. That is convenient and risky. Always check which values became missing.

Python pandas: find values lost in conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Int64 with a capital I is a pandas integer type that allows missing values. By default, a numeric column of whole numbers with a gap becomes floating point. See pandas data types.

A conversion routine

  1. Keep the original text column.
  2. Convert into a new column.
  3. List the failures with counts and examples.
  4. Fix rules or send records for review.
  5. Check ranges and totals after conversion.

Common mistake: returning a default such as 0 inside an except block. Every unreadable value then looks like a real zero.

Decide what happens to failures

A parser should tell you three different outcomes apart: a converted value, a value that is truly missing and a value that is present but unreadable. If the last two both become empty, you cannot tell how much information you lost. One practical design is to write failures to a report with the row ID, the column, the original text and the reason.

Then group failures by their text or shape. You will often find that a few patterns explain most of them, such as a currency symbol or a note typed into a number column. Add a rule for each pattern that you understand and can defend. Leave the rest for review. A rule that tries to extract digits from anything will happily turn "room 12, floor 3" into a number.

Ranges after conversion

A value can convert without error and still be wrong. If a source switched from dot decimals to comma decimals, some values may parse successfully but be a thousand times too large. Compare the new column's minimum, maximum, median and total with earlier deliveries. A sudden change in scale is a strong signal that the format rule no longer fits.

Rounding

Decide when to round, and how. Rounding each line and then adding can differ from adding first and rounding once. Different systems also use different rules for values exactly halfway. Python's built-in round uses round-half-to-even for exact halves, and floating point representation can make a value look like a half when it is not. For money, use Decimal with an explicit rounding mode that matches your organization's rule, and keep unrounded values where you can.

Types and file formats

CSV stores only text, so your types are lost each time you save to it. Keep a schema that lists each column's type and apply it when you load. Some binary formats store types with the data, which avoids repeating the guesswork. See data formats if you are choosing one.

Check totals both ways

If the source provides a control total, calculate the same total from your converted column and include the failed rows in your explanation. A difference equal to the failed values tells you that your conversion is consistent. Any other difference means something converted wrongly, perhaps a separator or a sign, so find it before you continue.

Convert once

Convert each column in one place in your code. If several scripts parse the same text in their own ways, they will sooner or later disagree about the same value. A single tested function gives everyone one answer.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does bool('False') return in Python?

    Non-empty strings are truthy, so you must map words explicitly.
  2. 2. After coercing a column to numbers, what should you do?

    Coercion hides failures unless you compare before and after.
  3. 3. Which is a good choice for exact decimal money arithmetic in Python?

    Decimal represents decimal fractions exactly, within its precision, when created from strings.

Summary

  • Choose a type for every column and keep IDs as text.
  • Tell the parser which number format the source uses.
  • Map booleans explicitly and keep unknown separate.
  • Surface every failed conversion.

Next: Cleaning Text with Python and Regex

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.