CSV 파일 읽기
pd.read_csv로 CSV 파일을 불러오고 구분자, 헤더 행, 인덱스 열을 제어한 뒤 결과를 미리 확인합니다.
CSV 파일 읽기은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why CSV Is the Universal Format
CSV (Comma-Separated Values) is the most widely used format for exchanging tabular data. It is human-readable, supported by every database, spreadsheet, and analytics tool, and requires no schema definition. pd.read_csv() is the most frequently called Pandas function in data analysis because virtually every public dataset, API export, or database dump is available in CSV.
import pandas as pd
# Read a CSV file from disk
df = pd.read_csv('data/sales.csv')
print(df.shape)
print(df.head())Basic read_csv() Call
The only required argument is the file path (string or Path object). By default Pandas assumes the first row is the header (column names), the delimiter is a comma, and values are inferred to appropriate dtypes. The resulting DataFrame has a default integer RangeIndex. Always call df.info() immediately after loading to spot type inference issues.
import pandas as pd
df = pd.read_csv('products.csv')
# Equivalent with explicit defaults:
df = pd.read_csv('products.csv',
sep=',',
header=0,
index_col=None)Controlling the Delimiter
Use the sep= parameter to specify a non-comma delimiter. Tab-separated files (TSV) use sep='\t'. Some European exports use semicolons as separators (sep=';') because commas are used as decimal separators. Pass sep=None, engine='python' to let Pandas auto-detect the separator from the file content.
import pandas as pd
# Tab-separated file
df_tsv = pd.read_csv('data.tsv', sep='\t')
# Semicolon-separated (common in Europe)
df_semi = pd.read_csv('data.csv', sep=';')
# Auto-detect separator
df_auto = pd.read_csv('data.txt', sep=None, engine='python')Header and skiprows
If a CSV has no header row, set header=None and Pandas will assign integer column names (0, 1, 2, ...). Provide custom names with names=['a', 'b', 'c']. Use skiprows=n to skip the first n rows (for metadata or comments at the top of the file). skiprows also accepts a list of specific row numbers to skip.
import pandas as pd
# CSV with no header
df = pd.read_csv('noheader.csv', header=None,
names=['id', 'value', 'category'])
# Skip first 3 rows (e.g., metadata or comments)
df = pd.read_csv('report.csv', skiprows=3)Setting the Index Column
index_col= specifies which column to use as the row index. Pass a column name or integer position. Setting a meaningful index (e.g., a date column or a unique ID) enables fast label-based access with .loc and is required before time-series operations. Pass a list for a MultiIndex.
import pandas as pd
# Use 'date' column as row index
df = pd.read_csv('timeseries.csv', index_col='date', parse_dates=True)
print(df.index.dtype) # datetime64[ns]
# Equivalent with column position
df2 = pd.read_csv('timeseries.csv', index_col=0, parse_dates=True)Parsing Dates on Load
parse_dates=True tells Pandas to try converting the index to datetime. Pass a list of column names to parse_dates=['col1', 'col2'] to parse specific non-index columns as dates. Pandas will try common formats automatically; for unusual formats use date_format=. Parsing dates at load time avoids repeated pd.to_datetime() calls later.
import pandas as pd
# Parse 'order_date' column as datetime
df = pd.read_csv('orders.csv',
parse_dates=['order_date'])
print(df['order_date'].dtype) # datetime64[ns]Selecting Columns with usecols
usecols=['col1', 'col2'] loads only the specified columns, ignoring all others. This is critical for large CSV files — there is no need to read a 200-column file if you only need 5 columns. It reduces both I/O time and memory usage significantly. Pass a callable to select columns by a name pattern.
import pandas as pd
# Load only 3 of potentially many columns
df = pd.read_csv('big_file.csv',
usecols=['user_id', 'event', 'timestamp'])
print(df.columns.tolist()) # ['user_id', 'event', 'timestamp']Controlling dtypes on Load
Pandas infers dtypes, but inference can be wrong — an ID column of all-numeric strings becomes int64, or a price column with missing values becomes float64 unexpectedly. Use dtype={'col': str} to enforce types. This is also more efficient: pre-specifying dtypes skips the inference pass and can speed up loading large files by 20-30%.
import pandas as pd
df = pd.read_csv('orders.csv', dtype={
'order_id': str, # keep as string (not int)
'price': float,
'quantity': 'int32' # use smaller int
})Handling Missing Values on Load
By default Pandas recognises many missing value representations: empty cells, 'NA', 'NaN', 'N/A', 'null', etc. Use na_values=['?', '-', 'missing'] to add custom tokens. Use keep_default_na=False to disable the built-in list and only treat the values you specify as missing. This prevents accidentally treating legitimate string values like 'NA' (an acronym) as NaN.
import pandas as pd
df = pd.read_csv('survey.csv',
na_values=['?', '', 'N/A', 'none'])
print(df.isnull().sum())nrows and chunksize for Large Files
nrows=100 loads only the first 100 rows — perfect for a quick schema check on a massive file. chunksize=10000 returns a TextFileReader iterator that yields DataFrames of 10000 rows each, enabling chunked processing of files that do not fit in RAM. Chunked reading is covered in depth in the advanced performance lesson.
import pandas as pd
# Quick peek at a large file
header_df = pd.read_csv('huge.csv', nrows=5)
print(header_df.dtypes)
# Chunked reading
for chunk in pd.read_csv('huge.csv', chunksize=50000):
print(chunk.shape) # process each chunkCommon Gotchas with read_csv
Watch out for these frequent issues: encoding errors (use encoding='utf-8' or 'latin-1'), leading spaces in column names (use skipinitialspace=True), thousands separators in numbers (use thousands=','), and decimal commas in European numbers (use decimal=',' and sep=';'). Each of these silently turns numeric columns into objects if ignored.
import pandas as pd
# European format: semicolon sep, comma decimal, UTF-8
df = pd.read_csv('euro_data.csv',
sep=';',
decimal=',',
thousands='.',
encoding='utf-8',
skipinitialspace=True)Quick Check
Test your understanding of reading CSV files with Pandas from this lesson.
Lesson Recap
In this lesson you learned: pd.read_csv() is the primary function for loading tabular data with many configuration parameters, sep, header, index_col, and parse_dates control how the file is interpreted, and usecols and dtype improve performance and type safety for large files. Next up we read Excel and JSON files, which have their own format-specific parameters.
자주 묻는 질문
“CSV 파일 읽기” 강의는 무료인가요?
네 — “CSV 파일 읽기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“CSV 파일 읽기”에서 뭘 배우나요?
pd.read_csv로 CSV 파일을 불러오고 구분자, 헤더 행, 인덱스 열을 제어한 뒤 결과를 미리 확인합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“CSV 파일 읽기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.