Sub topic 5
Loading data with read_csv and saving results
This chapter assumes you can build a DataFrame from Python data, know what an Index is, and know what a dtype is. You will use read_csv to load a table from text, control how columns are typed, and write results back out. The chapter runs about 1,200 words, and every example runs as shown.
What read_csv does
pd.read_csv parses delimited text into a DataFrame. It accepts a file path, a URL, or any file-like object. Every example below uses io.StringIO, which wraps a string so pandas treats it as a file. That keeps the examples self-contained.
import io
import pandas as pd
text = """city,pop_m,region
Oslo,0.7,EU
Lima,10.7,SA
Pune,3.1,AS
Rome,2.8,EU
"""
df = pd.read_csv(io.StringIO(text))
print(df)
print(df.dtypes)By default, pandas does the following:
- It uses the first line as column names.
- It creates a fresh
RangeIndex(0, 1, 2, ...). - It infers a dtype for each column from the values it sees.
Here city and region become object (or string, depending on your pandas version and settings), and pop_m becomes float64.
Inspecting what you loaded
Check the result right after loading. Errors in parsing are quiet, so a quick look saves debugging later.
import io
import pandas as pd
text = "city,pop_m\nOslo,0.7\nLima,10.7\n"
df = pd.read_csv(io.StringIO(text))
print(df.shape) # (2, 2)
print(df.head())
df.info() # column names, dtypes, non-null countsinfo() is the most useful check. A column you expected to be numeric but listed as object usually means some cell contained text.
Choosing the Index while loading
If one column identifies each row, make it the Index at load time with index_col.
import io
import pandas as pd
text = "city,pop_m\nOslo,0.7\nLima,10.7\n"
df = pd.read_csv(io.StringIO(text), index_col="city")
print(df.loc["Lima", "pop_m"]) # 10.7Only do this when the column has unique, meaningful labels. Otherwise keep the default RangeIndex.
Controlling dtypes and columns
Inference is convenient but can be wrong. Three parameters give you control:
| Parameter | Purpose |
|---|---|
| `usecols` | Load only the listed columns. |
| `dtype` | Set the dtype for named columns. |
| `parse_dates` | Convert the listed columns to datetimes. |
import io
import pandas as pd
text = """id,zip,amount,signup,note
1,01234,9.5,2024-01-05,x
2,98765,12.0,2024-02-10,y
"""
df = pd.read_csv(
io.StringIO(text),
usecols=["id", "zip", "amount", "signup"],
dtype={"zip": str},
parse_dates=["signup"],
)
print(df.dtypes)
print(df["zip"].tolist()) # ['01234', '98765']Without dtype={"zip": str}, the zip code 01234 would be read as the integer 1234, and the leading zero would be lost. Identifiers such as zip codes, phone numbers, and account numbers should be read as strings.
Setting dtypes at load time is better than converting afterward. It is faster, uses less memory, and avoids a wrong intermediate inference.
Missing values on input
read_csv already treats empty cells and strings such as NA, NaN, and null as missing. If your file uses other markers, name them with na_values.
import io
import pandas as pd
text = """name,score
Ana,90
Ben,-
Cy,75
"""
df = pd.read_csv(io.StringIO(text), na_values=["-"])
print(df["score"].isna().tolist()) # [False, True, False]
print(df["score"].dtype) # float64Without na_values, the - would make the whole score column object, because one text cell prevents numeric parsing. This is the most common cause of a numeric column loading as object. Missing values then flow into the tools from the missing-data chapter (isna, fillna, dropna).
Other format details
Files do not always follow the comma-and-header layout. These parameters cover the usual variations:
sep=";"orsep="\t"sets a different delimiter.header=Nonesays the file has no header row. Addnames=[...]to supply column names.skiprows=nskips lines at the top, such as a title or comment block.nrows=nreads only the first n rows, which is useful for a quick look at a large file.encoding="utf-8"(or"latin-1", and so on) sets the text encoding when characters decode wrongly.
import io
import pandas as pd
text = "a;b\n1;2\n3;4\n"
df = pd.read_csv(io.StringIO(text), sep=";")
print(df)Large files
If a file is too large to load at once, read it in pieces with chunksize. This returns an iterator of DataFrames instead of one DataFrame.
import io
import pandas as pd
text = "x\n" + "\n".join(str(i) for i in range(10)) + "\n"
total = 0
for chunk in pd.read_csv(io.StringIO(text), chunksize=4):
total += chunk["x"].sum()
print(total) # 45Each chunk is a normal DataFrame with its own RangeIndex continuing from the previous chunk. Process or aggregate each chunk, then combine the small results. Loading only the columns you need with usecols also cuts memory.
Writing results with to_csv
DataFrame.to_csv writes a DataFrame to a file, or returns a string when you give it no path.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima"], "pop_m": [0.7, 10.7]})
print(df.to_csv(index=False))The index=False argument matters. By default to_csv writes the Index as an extra first column. If you read that file back, the old index appears as an unnamed column called Unnamed: 0. Pass index=False when the Index is just a default RangeIndex. If the Index carries meaning, keep it and read it back with index_col.
A round trip
import io
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima"], "pop_m": [0.7, 10.7]})
text = df.to_csv(index=False)
back = pd.read_csv(io.StringIO(text))
print(back.equals(df)) # TrueA round trip through CSV is not always lossless. CSV stores only text, so dtype information is lost. A category column returns as object, and a datetime column returns as text unless you use parse_dates. If you must preserve dtypes exactly, use a binary format such as Parquet (to_parquet and read_parquet, which need the pyarrow or fastparquet package installed).
Writing options
columns=[...]writes only the listed columns, in that order.sep="\t"writes tab-separated output.na_rep="NA"sets the text written for missing values. The default is an empty string.float_format="%.2f"fixes the number of decimals.
import pandas as pd
df = pd.DataFrame({"x": [1.23456, None], "y": [1, 2]})
print(df.to_csv(index=False, na_rep="NA", float_format="%.2f"))Common errors
Unnamed: 0column. A file was saved with the Index and read withoutindex_col=0. Save withindex=False, or read withindex_col=0.- Lost leading zeros. An identifier column was inferred as integer. Use
dtype={"col": str}. - Numeric column loaded as
object. A stray text marker is in the data. Find it withdf["col"].unique()or add it tona_values. - Dates stay as text. Add
parse_dates=[...]. - Garbled characters. Set the right
encoding. - One column holds everything. The delimiter is wrong. Set
sep.
How the pieces fit
Exercises
Exercise
A CSV file has a column zip with values like 00501. After pd.read_csv, the values show as 501. What argument fixes this, and why does the problem occur?
Show answer
Pass dtype={"zip": str}. Without it, pandas infers the column as integer, and integers have no leading zeros, so 00501 becomes 501. Reading the column as a string keeps the text exactly.
Exercise
You save a DataFrame with df.to_csv("out.csv") and later read it with pd.read_csv("out.csv"). The result has an extra column named Unnamed: 0. Give two ways to avoid this.
Show answer
Save with df.to_csv("out.csv", index=False) so the Index is not written. Or keep the Index when saving and read it back with pd.read_csv("out.csv", index_col=0).
Exercise
A score column contains the numbers 90 and 75 and one cell with -. The column loads as object. How do you get a numeric column with a missing value instead?
Show answer
Pass na_values=["-"] to read_csv. The - is then read as missing (NaN), and the column becomes float64.