pandas / Basic: labels, types and accepted input / Lesson 7
CSV Export and Round-Trip Contracts
Specify a CSV export and verify that a consumer can read identifiers, missing values, and columns as intended.
On this page
Lesson goals
- Define an export schema and index policy.
- Round-trip a small CSV with explicit identifier types.
- Reconcile values and document CSV limitations.
- Specify paired CSV writer and reader options for identity, schema and missing values.
- Reconcile row-level and aggregate invariants after a synthetic round trip.
Define the exchange contract
CSV stores text fields rather than a complete pandas schema. Agree on column names, order, encoding, delimiter, quoting, missing-value representation, date format, and units with the consumer. Decide whether the index is meaningful data or an implementation detail; exporting it accidentally can create an unexpected column.
An identifier such as 001 should remain text when leading zeros matter. A successful file write does not prove that another reader will preserve types or interpret empty fields in the same way. Keep the source data and document the read settings needed to reconstruct the intended values.
Export a small fixture
In a local lab with pandas installed, the example creates two synthetic records and exports CSV text without an index column. It prints the text rather than modifying a file. The public reader does not execute the example; consult the installed version’s documentation for the available options.
import pandas as pd
frame = pd.DataFrame({"id": ["001", "002"], "amount": [10, 20]})
text = frame.to_csv(index=False)
print(text)
The CSV contains the id and amount columns, with identifiers written as their original text.
Read with explicit types
The second lab reads a fixed CSV string and explicitly requests a string type for the identifier. Inspect the restored values and dtypes, then compare with the original contract. Numeric inference may otherwise discard leading zeros, depending on input and parser settings. Tests should include missing values and quoted delimiters as well.
from io import StringIO
import pandas as pd
text = "id,amount\n001,10\n002,20\n"
restored = pd.read_csv(StringIO(text), dtype={"id": "string"})
print(restored["id"].tolist())
The explicit id type preserves the two identifier strings for comparison with the source.
Reconcile before delivery
Compare row and column counts, identifier uniqueness, missing-value counts, and important totals after reading the exported file. Check non-ASCII text and delimiters inside quoted fields with representative fixtures. A matching total alone can hide shifted columns or duplicated rows, so inspect individual records and types too.
Document limitations
CSV does not retain every dtype, category ordering, timezone convention, or metadata item automatically. Supply a separate data dictionary and explicit parsing settings, or choose a format that meets the consumer’s needs. Version the export contract and agree how breaking changes will be communicated and tested before replacing a shared extract.
Treat exchange as a two-sided contract
Exporting a DataFrame to CSV creates text, not a complete pandas schema. The producer and consumer must agree on the row grain, field names and order, identity, delimiter, quote and escape rules, character encoding, missing token, numeric units and date or timezone representation. A file can be well formed and still violate that agreement. Decide whether the index is an implementation detail or contains an essential business key. If the key exists only in a named index, expose it as a column or explicitly export and label the index; index=False alone would lose it.
A code such as 001 is an identifier when its leading zeros distinguish entities. The producer may write those characters correctly, yet a consumer that infers an integer can recover 1. Specify the consumer’s dtype and compare restored values, not just the output text. A round trip also has an explicit population: establish expected keys and row count before comparing totals. A sum can match while a duplicate and an omitted record cancel each other, or while rows are reordered contrary to the report contract.
Write a reproducible in-memory representation
DataFrame.to_csv can return a string when no destination is passed. That makes a small synthetic round trip inspectable without changing a real file. Set index=False when the required identities are already columns, specify columns in the required order, and set a line terminator when byte-for-byte representation is part of the test. CSV quoting protects embedded delimiters, quotation marks and newlines according to the chosen dialect. Use a CSV reader to reconstruct logical records; splitting lines or commas manually cannot reliably parse quoted content.
Writing an index is not inherently wrong. If a consumer requires a named key column, reset a named index before selecting output columns, or use an agreed index label and matching read settings. Verify that the key appears once rather than as both a column and a duplicate index field. Check the actual header and row order, because default index serialization can add an unexpected field and sorting upstream can alter the order without changing values.
Make missing and literal values distinguishable
The default CSV representation of a missing value can be indistinguishable from an empty text field to a consumer. If the domain needs to distinguish empty text from missing, agree on a sentinel that is forbidden as a literal value or define an escaping convention. Set na_rep when writing and matching na_values and keep_default_na options when reading. A literal value equal to the chosen sentinel is a collision: the consumer cannot reliably infer which occurrence represented missingness without additional information. Reject or escape that collision before export.
Similarly, configure each column’s dtype and missing-token policy on import. A token that means missing in quantity may be a valid identifier. Nullable Int64 can restore integral quantities with a missing value when parser options and the source contract support it. Compare missing masks as well as observed values and dtype. Do not automatically replace unknown quantities with zero for a convenient sum; report the observed count and an explicit minimum-count policy.
Trace a complete synthetic round trip
The program below creates two synthetic records: code 001 with quantity 2 and note "red, small", and code 002 with a missing quantity and note "blue". It exports only the stated columns, without a DataFrame index, using <MISSING> as the agreed missing token. read_csv uses string identifiers, a nullable integer quantity, and a column-specific missing rule while disabling default NA recognition. Assertions compare the exact identifiers, notes and missingness. The quoted comma is restored within one field, and the observed quantity sum is 2 with one known value.
The sentinel is safe only because this fixture has no literal <MISSING> in quantity. A production contract should check collision against all relevant text fields and identify which columns apply the missing rule. A successful self-round-trip through pandas demonstrates only this pair of writer and reader settings; a different consumer may use different parsing rules. Exchange fixtures with the actual consumer and independently validate expected keys, row count, types, domain constraints and totals.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':pd.Series(['001','002'],dtype='string'), 'qty':pd.Series([2,None],dtype='Int64'), 'note':['red, small','blue']})
text = f.to_csv(index=False, columns=['id','qty','note'], na_rep='<MISSING>', lineterminator='\n')
r = pd.read_csv(StringIO(text), dtype={'id':'string','qty':'Int64','note':'string'}, keep_default_na=False, na_values={'qty':['<MISSING>']})
assert r['id'].tolist() == ['001','002']
assert r['note'].tolist() == ['red, small','blue']
assert r['qty'].isna().tolist() == [False, True]
print(r['id'].tolist(), r['qty'].count(), r['qty'].sum(min_count=1))
['001', '002'] 1 2
The identifiers, quoted note and missing quantity survive the explicitly paired settings. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Reconcile values, metadata and evidence
A useful acceptance report compares ordered column names, row count, unique nonmissing keys, expected and unexpected keys, missing counts and representative per-key values. Compare numeric totals only after those checks; an aggregate can remain unchanged despite structural corruption. If row order matters, compare the ordered key list as well as the set. Test non-ASCII text with an agreed encoding, quoted delimiters and embedded newlines, and a deliberate missing-token collision. Treat a mismatch as a reason to stop or reconcile, not as an invitation to overwrite the original evidence.
CSV does not automatically preserve all pandas dtypes, categories, timezone semantics, precision or metadata. Supply a versioned data dictionary and agreed reader options, or choose another format when the consumer needs guarantees CSV cannot provide. The selected course baseline is pandas 3.1.0; official writer and reader documentation consulted during authoring identified itself as 3.1.1. Standalone examples are qualified separately using synthetic in-memory inputs, with exact runtime versions recorded. No real dataset, external service or shared extract is modified by these examples. These standalone programs were executed in that isolated environment.
20 worked examples
1. Export without index
Problem: Write two fields as in-memory CSV without a numeric index.
- The DataFrame contains id and qty as ordinary columns.
- index=False excludes the default numeric index from the text.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['A'], 'qty':[2]})
print(f.to_csv(index=False, lineterminator='\n'), end='')
id,qty
A,2
The emitted schema consists of the two requested data columns. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The emitted schema consists of the two requested data columns.
2. Restore text ID
Problem: Read an exported leading-zero identifier with an explicit string dtype.
- The CSV text contains the characters 004.
- The reader requests string for id and preserves those characters.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['004'], 'qty':[2]})
t = f.to_csv(index=False)
r = pd.read_csv(StringIO(t), dtype={'id':'string'})
print(r['id'].tolist())
['004']
The read contract preserves identifier formatting that numeric inference could discard. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The read contract preserves identifier formatting that numeric inference could discard.
3. Output column order
Problem: Export qty before id using an explicit column list.
- The output projection contains qty and id only.
- Its list order places qty before id in the emitted text.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['A'], 'qty':[2], 'note':['ok']})
t = f.to_csv(index=False, columns=['qty','id'], lineterminator='\n')
print(t, end='')
qty,id
2,A
The columns argument defines both the projection and order. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The columns argument defines both the projection and order.
4. Export a named index
Problem: Write a named item index as an explicit CSV field.
- The item identity is stored in the named index.
- Including the index writes item and A as the first field.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'qty':[2]}, index=pd.Index(['A'], name='item'))
t = f.to_csv(index=True, lineterminator='\n')
print(t, end='')
item,qty
A,2
A named exported index can carry a required business key. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A named exported index can carry a required business key.
5. Reset before export
Problem: Turn a business index into a regular field before export.
- reset_index restores A as a value in the item column.
- index=False omits the new default numeric index.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'qty':[2]}, index=pd.Index(['A'], name='item'))
t = f.reset_index().to_csv(index=False, lineterminator='\n')
print(t, end='')
item,qty
A,2
The identity remains in the data schema without an extra numeric field. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The identity remains in the data schema without an extra numeric field.
6. Quoted comma round trip
Problem: Restore a note containing a comma as one field.
- The writer quotes the note because it contains the delimiter.
- The reader restores the comma inside one note cell.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'note':['red, small']})
t = f.to_csv(index=False)
r = pd.read_csv(StringIO(t))
print(r.loc[0,'note'], r.shape)
red, small (1, 1)
Matching CSV writer and reader rules preserve the embedded delimiter. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Matching CSV writer and reader rules preserve the embedded delimiter.
7. Embedded newline round trip
Problem: Restore a two-line note as one logical record.
- The newline is part of the quoted note field.
- The reader produces one row and retains both lines in the value.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'note':['first\nsecond']})
t = f.to_csv(index=False)
r = pd.read_csv(StringIO(t))
print(len(r), r.loc[0,'note'].splitlines())
1 ['first', 'second']
A logical CSV record can span more than one physical line. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A logical CSV record can span more than one physical line.
8. Quote round trip
Problem: Restore text containing an embedded double quote.
- The writer encodes the embedded quotation marks in CSV text.
- The reader reconstructs the original text including both marks.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'note':['say "hi"']})
t = f.to_csv(index=False)
r = pd.read_csv(StringIO(t))
print(r.loc[0,'note'])
say "hi"
The paired quoting rules preserve literal quote characters. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The paired quoting rules preserve literal quote characters.
9. Missing token agreement
Problem: Round-trip a missing quantity with a dedicated token.
- The writer represents the absent quantity with the agreed token.
- The reader maps that token back to missing in qty only.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'qty':pd.Series([2,None],dtype='Int64')})
t = f.to_csv(index=False, na_rep='<MISSING>')
r = pd.read_csv(StringIO(t), dtype={'qty':'Int64'}, keep_default_na=False, na_values={'qty':['<MISSING>']})
print(r['qty'].isna().tolist())
[False, True]
Paired writer and reader settings preserve this missingness mask. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Paired writer and reader settings preserve this missingness mask.
10. Sentinel collision
Problem: Detect a literal note that conflicts with the proposed missing token.
- The first note literally equals the intended sentinel.
- Without an escape rule it could be confused with a missing value.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'note':['<MISSING>','blue']})
print(f['note'].eq('<MISSING>').tolist())
[True, False]
A collision check prevents an ambiguous exchange contract. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A collision check prevents an ambiguous exchange contract.
11. Nullable integer recovery
Problem: Restore an observed integer and a missing quantity with Int64.
- The reader maps ? to missing and requests nullable integers.
- Only the value 7 is observed, so count is one.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'qty':pd.Series([7,None],dtype='Int64')})
t = f.to_csv(index=False, na_rep='?')
r = pd.read_csv(StringIO(t), dtype={'qty':'Int64'}, keep_default_na=False, na_values={'qty':['?']})
print(str(r['qty'].dtype), r['qty'].count())
Int64 1
The reader reconstructs the declared dtype and observed count. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The reader reconstructs the declared dtype and observed count.
12. UTF-8 round trip
Problem: Encode a non-ASCII label to UTF-8 and restore it.
- The CSV string is encoded to UTF-8 bytes in memory.
- The reader uses the same encoding and restores café.
from io import StringIO
import pandas as pd
from io import BytesIO
f = pd.DataFrame({'name':['café']})
b = f.to_csv(index=False).encode('utf-8')
r = pd.read_csv(BytesIO(b), encoding='utf-8')
print(r.loc[0,'name'])
café
An agreed encoding preserves the non-ASCII character in this fixture. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: An agreed encoding preserves the non-ASCII character in this fixture.
13. Semicolon round trip
Problem: Write and read two fields with a semicolon delimiter.
- The writer separates fields with a semicolon.
- The reader uses the same separator and restores qty as 2.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['A'], 'qty':[2]})
t = f.to_csv(index=False, sep=';')
r = pd.read_csv(StringIO(t), sep=';')
print(r.columns.tolist(), r.loc[0,'qty'])
['id', 'qty'] 2
The delimiter must be shared by both sides of the exchange. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The delimiter must be shared by both sides of the exchange.
14. Decimal convention
Problem: Round-trip a decimal-comma value with semicolon fields.
- The writer represents 1.5 with a decimal comma in the text.
- The reader applies the matching decimal convention to recover 1.5.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'price':[1.5]})
t = f.to_csv(index=False, sep=';', decimal=',')
r = pd.read_csv(StringIO(t), sep=';', decimal=',')
print(r.loc[0,'price'])
1.5
Matching numeric conventions preserve the value in this example. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Matching numeric conventions preserve the value in this example.
15. Explicit date text
Problem: Write and restore a date using a declared date representation.
- The writer formats the date as year-month-day text.
- The reader restores that representation as an explicit string.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'day':pd.to_datetime(['2025-01-02'])})
t = f.to_csv(index=False, date_format='%Y-%m-%d')
r = pd.read_csv(StringIO(t), dtype={'day':'string'})
print(r.loc[0,'day'])
2025-01-02
The text representation is preserved; datetime metadata needs a separate contract. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The text representation is preserved; datetime metadata needs a separate contract.
16. Ordered key check
Problem: Verify row order after an in-memory export and read.
- The writer receives B before A.
- The reader restores the same two records in that order.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['B','A'], 'qty':[2,3]})
r = pd.read_csv(StringIO(f.to_csv(index=False)))
print(r['id'].tolist())
['B', 'A']
An ordered key list checks a stronger condition than an unordered set. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: An ordered key list checks a stronger condition than an unordered set.
17. Duplicate-key detection
Problem: Detect duplicate IDs after reading exported records.
- Both exported rows have the identifier A.
- The restored id column is therefore not unique.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['A','A'], 'qty':[2,3]})
r = pd.read_csv(StringIO(f.to_csv(index=False)))
print(r['id'].is_unique)
False
Round-trip fidelity alone does not establish a valid source key. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Round-trip fidelity alone does not establish a valid source key.
18. Missing-count reconciliation
Problem: Compare missing quantity counts before and after export.
- The source contains one missing quantity among three rows.
- The matching import policy restores one missing quantity.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'qty':pd.Series([2,None,5],dtype='Int64')})
t = f.to_csv(index=False, na_rep='?')
r = pd.read_csv(StringIO(t), dtype={'qty':'Int64'}, keep_default_na=False, na_values={'qty':['?']})
print(f['qty'].isna().sum(), r['qty'].isna().sum())
1 1
Comparing missing counts checks one part of the round-trip contract. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Comparing missing counts checks one part of the round-trip contract.
19. Total is not enough
Problem: Detect a duplicated zero-valued row despite an unchanged sum.
- Duplicating B adds zero to the sum, leaving both totals at 5.
- The row count rises from two to three, exposing the duplicate.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['A','B'], 'qty':[5,0]})
r = pd.concat([f, f.iloc[[1]]], ignore_index=True)
print(f['qty'].sum(), r['qty'].sum(), len(f), len(r))
5 5 2 3
Reconciliation must include identity and row count as well as totals. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Reconciliation must include identity and row count as well as totals.
20. End-to-end reconciliation
Problem: Round-trip keyed quantities and verify schema, keys and sum.
- Explicit id typing preserves both leading-zero keys.
- The restored two rows have unique IDs and quantities totaling five.
from io import StringIO
import pandas as pd
f = pd.DataFrame({'id':['001','002'], 'qty':[2,3]})
t = f.to_csv(index=False, columns=['id','qty'])
r = pd.read_csv(StringIO(t), dtype={'id':'string','qty':'Int64'})
assert r.columns.tolist() == ['id','qty'] and r['id'].is_unique
print(r['id'].tolist(), len(r), r['qty'].sum())
['001', '002'] 2 5
Schema, identity, count and total checks cover distinct failure modes. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Schema, identity, count and total checks cover distinct failure modes.
Common errors and fixes
A leading-zero identifier becomes a number.
- Why it happens
- The consumer inferred a numeric dtype.
- How to fix it
- Read the identifier explicitly as text and compare values.
- Prevent it next time
- Publish identifier types and include leading-zero fixtures.
An extra unnamed column appears after import.
- Why it happens
- The index was exported unintentionally.
- How to fix it
- Set the intended index export policy and regenerate the test file.
- Prevent it next time
- Include expected columns in the exchange contract.
Missing and empty text values become indistinguishable.
- Why it happens
- The export and import did not specify a shared representation.
- How to fix it
- Agree on an unambiguous encoding and test both cases.
- Prevent it next time
- Include missing-value handling in round-trip checks.
20 practice exercises
1. Why can a CSV containing 001 be read back as 1?
Show hint
Distinguish the written characters from the reader’s inferred dtype.
Show worked solution
A reader may infer a numeric type and discard leading zeros. Specify the identifier as text on import and compare the restored value with the original.
The CSV can contain the characters 001, but numeric inference interprets them as integer 1. Read the identifier with an explicit string dtype and compare the restored text and expected key set with the source.
Check your solution
- The source text contains 001.
- The explicit text read restores 001, not numeric 1.
2. A round-trip preserves the total amount but the row count doubles. Is the export accepted?
Show hint
A matching aggregate is only one invariant.
Show worked solution
No. Investigate duplicate records or a parsing mismatch and reconcile row count, keys, types, and totals before delivery. A matching total is only one check.
Reject the exchange until the doubled rows are explained. Check for duplicate identities and parsing differences, then reconcile row count, exact keys, types, missingness and per-key values as well as the total.
Check your solution
- The restored row count differs from the source.
- A matching total does not establish identity or uniqueness.
3. A frame stores IDs P,Q only in a named item index and has a qty column. Design an index-free CSV that retains identity.
Show hint
Move the index into a data column first.
Show worked solution
Use f.reset_index().to_csv(index=False). The exported columns include item and qty, and P,Q remain in item; verify the header and keys after reading instead of applying index=False directly to the original frame.
Check your solution
- The CSV contains an item field.
- Both P and Q survive the exchange.
4. IDs "004" and "04" must remain distinct after CSV exchange. Specify reader dtype and two checks.
Show hint
Treat the identifiers as text on reading.
Show worked solution
Read id with dtype={"id":"string"}, then check the restored list is ["004","04"] and its values are unique. Numeric inference could turn both into 4, so a successful parse or numeric total alone cannot validate identity.
Check your solution
- The exact restored strings are 004 and 04.
- The restored ID count is two distinct values.
5. A consumer expects item,qty, but the export has qty,item,internal. Repair the projection and validate required keys.
Show hint
Select the exact ordered schema before writing.
Show worked solution
Export frame[["item","qty"]] with index=False after checking the item column contains the expected keys. Verify the output header is item,qty and that internal is intentionally omitted; a reordered header may break a positional consumer.
Check your solution
- The emitted header is item,qty.
- The item keys remain present.
6. An index is named item but the consumer requires the field name product_id. Choose an export option and verify the header.
Show hint
The exported index label is part of the schema.
Show worked solution
Use to_csv(index=True, index_label="product_id") when the index holds the required key and no duplicate product_id column exists. Check that the first header field is product_id and its values match the original index.
Check your solution
- The first header field is product_id.
- Index values are preserved as that field.
7. A frame has keys P,Q only in its index. A pipeline resets with drop=True before writing. Diagnose and repair.
Show hint
The discarded labels have no remaining copy.
Show worked solution
The reset discards P and Q and replaces them with a default integer index, so the output cannot identify the original records. Recover the original frame, reset without drop, then export the key column and check both identities.
Check your solution
- The dropped frame alone no longer contains P,Q.
- The repaired output includes both original keys.
8. A note is "blue, large" and the CSV delimiter is comma. Explain why a CSV parser and not split(",") is required.
Show hint
The delimiter inside quotes belongs to the field.
Show worked solution
The writer quotes the note so a CSV reader reconstructs one field containing blue, large. A naive comma split treats its embedded comma as a boundary and creates extra pieces; verify the restored note and the expected column count.
Check your solution
- The restored note is one value.
- The parsed row retains the expected number of columns.
9. A header plus two records includes one quoted note spanning three physical lines. Determine physical lines and logical data rows.
Show hint
A quoted newline does not end the record.
Show worked solution
There are five physical lines: one header, three for the first record and one for the second. There are two logical data rows. Reconcile using a CSV parser’s records rather than assuming each physical line is one record.
Check your solution
- The physical line count is 5.
- The logical data-row count is 2.
10. A note value is the literal text say "yes". Design a round-trip check for both quote characters. The consumer strips quote characters after parsing; describe the resulting defect and a check that catches it.
Show hint
Let the CSV writer and reader handle quoting.
Show worked solution
Export the note using to_csv and read it with read_csv under matching quoting rules. Assert the restored value equals the original say "yes", including both quotation marks; inspecting the escaped CSV text alone is not a value-level check. The restored value would become say yes instead of say "yes"; exact per-field equality with the raw note catches the loss.
Check your solution
- The restored text contains the opening quote.
- It also contains the closing quote and matches the original.
- The expected note includes both literal quote characters.
11. A text column contains values blue and green plus a missing entry. Propose a missing token and a pre-export collision check.
Show hint
Choose a reserved token absent from valid text values.
Show worked solution
Reserve <MISSING> as the missing token, check that no nonmissing source value equals it, and document that restriction. Write na_rep="<MISSING>" and configure the matching column-specific read rule so blue, green and missing remain distinct.
Check your solution
- Neither blue nor green collides with the token.
- The restored missing mask has one true entry.
12. An output token NA can mean either literal region code NA or missing region. Can the receiver reconstruct both meanings without extra information?
Show hint
The same text token represents two different source states.
Show worked solution
No. If both states serialize identically, a reader cannot determine which occurrence was literal. Reject the collision, reserve a different missing token or use an agreed escaping or separate indicator, then test both states with the actual consumer.
Check your solution
- Literal NA and missing are ambiguous under the same token.
- A revised contract must encode the states distinctly.
13. Quantities [0, missing, 4] are exported with ? as the missing token. Specify the read dtype and reconciliation counts.
Show hint
An observed zero must remain distinct from missing.
Show worked solution
Read qty as Int64 with keep_default_na=False and a column-specific ? missing rule. The restored values have two observations, one missing and one observed zero. Compare dtype and the complete missing mask with the source.
Check your solution
- Restored dtype is Int64.
- There are two observed values and one missing value.
14. An export contract requires UTF-8, but a receiver reports a decoding error. Design the response without altering the source bytes.
Show hint
Preserve evidence and verify both sides use the agreed encoding.
Show worked solution
Quarantine the bytes and confirm the writer actually encoded UTF-8 and the reader used strict UTF-8 decoding. If the bytes are invalid, obtain a corrected extract or agreed encoding; do not silently replace characters because that can corrupt identifiers.
Check your solution
- Original bytes are retained for diagnosis.
- No replacement-character output is accepted as faithful identity.
15. A producer writes id;qty followed by A;4. Specify compatible reader options and the recovered value. A second row B has missing qty represented by ?; add matching writer and reader settings and identify its restored state.
Show hint
The same field delimiter is needed on both sides.
Show worked solution
Use sep=";" for both to_csv and read_csv. The reader obtains columns id and qty, with A and numeric quantity 4; assert the header and quantity after reading so a delimiter mismatch is detected. Write na_rep="?" and read qty with na_values={"qty":["?"]} and an agreed default-token policy; B’s quantity is missing, not zero.
Check your solution
- The recovered columns are id and qty.
- The recovered quantity is 4.
- B’s restored quantity is missing under the paired policy.
16. A value 1.234 is exported as 1.23 under a two-decimal formatting policy. What precision check is needed?
Show hint
Distinguish a deliberate rounding rule from exact preservation.
Show worked solution
The restored decimal text represents 1.23, not the original 1.234. Accept it only if the agreed rounding and tolerance permit the 0.004 difference; otherwise export sufficient precision and compare restored values against the original contract.
Check your solution
- The displayed value is 1.23.
- The absolute difference from 1.234 is 0.004.
17. A timestamp string includes an offset +02:00. Does writing and reading its text alone prove the original timezone metadata survived?
Show hint
An offset string and a named timezone are different claims.
Show worked solution
No. The characters can survive while the reader reconstructs a different dtype or loses a named timezone and its rules. Specify the representation, parse it with an agreed timezone policy, and verify both the instant and required metadata independently.
Check your solution
- The text can preserve +02:00.
- A named timezone requires separate reconstruction and verification.
18. Source rows are A=2,B=3; restored rows are B=2,A=3. The sum is still 5. Which checks reveal the error?
Show hint
Compare ordered keys and values by key, not just the aggregate.
Show worked solution
The source order A,B differs from restored order B,A, and the values are attached to opposite keys: A changed from 2 to 3 and B from 3 to 2. Check both ordered identities and a per-key value mapping; the equal total hides both changes.
Check your solution
- Both totals are 5.
- A and B have swapped quantities after restoration.
19. Expected IDs are A,B,C; a restored file contains A,A,None. Design uniqueness, missing-key and coverage checks.
Show hint
Check duplicates and missingness before converting keys to a set.
Show worked solution
The restored IDs contain duplicate A and a missing key. After rejecting or reconciling those defects, compare observed nonmissing keys with {A,B,C}; B and C are absent. Set comparison alone would hide the repeated A.
Check your solution
- A is duplicated and one ID is missing.
- Expected IDs B and C are absent.
20. Export records 001=(qty 2, note "red, small") and 002=(missing, "blue"). Design acceptance with expected keys and observed sum.
Show hint
Specify typed IDs, a collision-free missing token and CSV quoting.
Show worked solution
Export id,qty,note without a redundant index, reserve a noncolliding quantity missing token, and read id as string and qty as Int64. Verify exact keys [001,002], the quoted note, one missing quantity, two rows and observed sum 2; compare the keys to an independent expectation.
Check your solution
- The two exact keys and note are restored.
- One quantity is missing and the observed sum is 2.
Key takeaways
- CSV requires an explicit exchange contract.
- Export and import settings must preserve identifier meaning.
- Reconcile schema, records, and totals after a round trip.
- CSV text alone does not preserve a complete dtype or metadata contract.
- Missing-token collisions must be prevented or encoded explicitly.
- Row count, key identity and per-key values complement aggregate checks.