सामग्री पर जाएँ

लेसन 3 · Getting Started

Reading Messy Files

Read messy CSV files safely: handle text encodings, byte order marks, delimiters, quoted fields, title rows, footers and wide layouts before you clean values.

Many "data problems" are really reading problems. A file opened with the wrong encoding turns accented names into strange symbols. A wrong delimiter squeezes a whole row into one column. Before you clean values, make sure you loaded them correctly.

Text encodings

A file is a sequence of bytes. An encoding says how bytes become characters. UTF-8 is the usual choice today, but older systems may export encodings such as Windows-1252. If you decode with the wrong one, you get an error or, worse, garbled text that looks almost right.

Python Same bytes, different encodings

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 last two lines show the byte order mark (BOM), an invisible character that some programs put at the start of a file. With plain utf-8 your first column is named id, so looking up id fails. Python's utf-8-sig codec removes it.

Do not repair garbled text by replacing symbols one by one. Go back and decode the original bytes correctly. If you do not know the encoding, ask the sender.

Delimiters and quotes

CSV looks simple, but fields can contain commas, quotes and line breaks. Do not split lines with line.split(","). Use a real CSV parser, such as Python's csv module. In many regions, exports use semicolons as the delimiter because the comma is the decimal mark.

Python Skip title rows and parse quoted fields

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 footer is not data, but it is useful: its total is a free check on what you read. Be careful with 1.500. Here it means fifteen hundred, not one and a half. Only the sender or the file's documentation can settle that.

Load as text first

Automatic type guessing can destroy information: 00742 becomes 742, and a long account number may lose digits. A safe habit is to load everything as text, then convert column by column with explicit rules. In pandas:

Python pandas: read every column as text

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.

In the first table pandas turns the ZIP codes into numbers and treats NA as missing. If NA is a real code, such as Namibia's country code, that is data loss. In the second table, every value stays as written, including empty strings. You then decide what counts as missing.

Layout problems

Check the shape of the table. A cleaning-friendly table follows three ideas, often called tidy data:

  1. Each variable has its own column.
  2. Each observation has its own row.
  3. Each kind of record has its own table.

Reports often break these rules, with one column per month, merged headers or two facts in one cell (Lima, PE). You can turn month columns into rows:

Python Reshape wide data into long data

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.

In pandas, the melt method does the same job. The pandas tutorial covers reshaping in more depth.

Common mistake: using an option that silently skips bad lines. If you skip any, count them, save them to a separate file and read some of them.

A loading checklist

  • Which encoding, delimiter and quote character does the file use?
  • Where do the headers start, and is there a footer?
  • Does the row count match what the source reports?
  • Are IDs and codes still text?
  • Do non-English characters look right?

Write the answers down next to your loading code. When the next file arrives and something differs, you will know what changed.

Inspect the raw text

Before you configure a parser, look at the first and last lines of the file in a plain text editor or print them in Python. In a few seconds you can see the delimiter, whether there are title lines above the header, whether quotes are used and whether summary rows sit at the bottom. For a very large file, read only a few lines instead of loading everything.

When you open files in Python, pass the encoding explicitly, for example open(path, encoding="utf-8", newline=""). Relying on a default can give different results on different computers. The newline="" argument is what the csv module documentation asks for, so that line breaks inside quoted fields are handled correctly.

Check what arrived

A successful load does not prove a correct load. Compare a few things with the source:

Check What it catches
Number of data rows Truncated files, skipped lines
Number of fields in each row Broken quoting, stray delimiters
First and last record Header or footer mistakes
A control total Wrong number format, missing rows
A few non-English names Encoding errors

With csv.DictReader, a row with too many fields keeps the extra ones under the key None, and a row with too few gets None for the missing values. Check for both instead of ignoring them.

Other formats

Spreadsheet files can contain several sheets, hidden rows, merged cells and formulas whose stored results may be out of date. JSON can nest lists inside records, so you must decide how to turn them into rows. In every format the advice is the same: find out what one record is, keep the source unchanged and verify counts after loading.

Treat files from unknown senders with care. Do not enable macros just to read data.

When loading fails

Read the error message and note the line number. Open the file around that line instead of switching on a "skip errors" option. A stray quote earlier in the file is a common cause, and the reported line may come later than the real problem.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Your first column name starts with an invisible character. What is a likely cause?

    A BOM at the start of a UTF-8 file sticks to the first header unless you remove it, for example with utf-8-sig.
  2. 2. Why not split CSV lines on commas yourself?

    A proper CSV parser understands quoting rules.
  3. 3. Why load identifier columns as text?

    Identifiers are labels, not quantities, so keep their exact characters.

Summary

  • Get encoding, delimiter and header position right first.
  • Use a CSV parser, and use footers as checks.
  • Load as text, then convert deliberately.
  • Reshape reports so each row is one observation.

Next: Profiling a Dataset

आपकी प्रगति इसी ब्राउज़र में सेव होती है। खाते की ज़रूरत नहीं है।