Excel 및 JSON 파일 읽기
pd.read_excel로 Excel 통합 문서를, pd.read_json으로 JSON 레코드를 가져오고 일반적인 형식 차이를 처리합니다.
Excel 및 JSON 파일 읽기은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Excel and JSON Matter
While CSV is the universal format, Excel files (.xlsx/.xls) are the dominant format for business data shared via email and reporting tools. JSON is the native format of REST APIs and NoSQL databases. Pandas provides pd.read_excel() and pd.read_json() that mirror the CSV reader's API, so skills transfer directly.
import pandas as pd
# The three most common load functions share the same philosophy
df_csv = pd.read_csv('data.csv')
df_excel = pd.read_excel('data.xlsx')
df_json = pd.read_json('data.json')Installing the Excel Engine
Reading Excel files requires an engine: openpyxl for .xlsx files (modern format) and xlrd for older .xls files. Install with pip install openpyxl. Pandas auto-selects the engine based on the file extension. For writing, use xlsxwriter for advanced formatting. Without the engine installed, read_excel() raises a ModuleNotFoundError.
# Install the required engine:
# pip install openpyxl # for .xlsx (modern)
# pip install xlrd==1.2.0 # for .xls (legacy)
import pandas as pd
df = pd.read_excel('report.xlsx', engine='openpyxl')Selecting a Sheet with sheet_name
Excel workbooks can have multiple sheets. sheet_name= specifies which one to read: pass a string (sheet name), an integer (0-based position), or a list to read multiple sheets into a dict. Pass sheet_name=None to read all sheets into a dict keyed by sheet name. Inspecting the available sheets with pd.ExcelFile('file.xlsx').sheet_names is a good starting point.
import pandas as pd
# Read the second sheet
df = pd.read_excel('workbook.xlsx', sheet_name=1)
# Read by name
df = pd.read_excel('workbook.xlsx', sheet_name='Sales')
# Inspect available sheets
xl = pd.ExcelFile('workbook.xlsx')
print(xl.sheet_names) # ['Summary', 'Sales', 'Costs']Common Excel Parameters
pd.read_excel() supports most of the same parameters as read_csv(): header=, index_col=, usecols=, skiprows=, dtype=, and nrows=. For Excel, usecols also accepts an Excel column range string like 'A:C' or 'A,C,E', which is convenient when the column letters are known from the spreadsheet layout.
import pandas as pd
df = pd.read_excel(
'sales_report.xlsx',
sheet_name='Q1',
header=2, # header is on row 3 (0-indexed)
usecols='A:D', # Excel column range
skiprows=[3, 4], # skip rows 4 and 5
nrows=100
)Reading JSON: Orient Formats
pd.read_json() reads JSON into a DataFrame. The orient= parameter specifies the JSON structure: 'records' (list of row dicts), 'columns' (dict of column arrays, the default), 'index' (dict of row dicts keyed by index), or 'values' (raw array). Most REST APIs return 'records' format — always inspect the raw JSON first to determine the correct orient.
import pandas as pd
# REST API response: list of records
json_str = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]'
df = pd.read_json(json_str, orient='records')
print(df)Reading JSON from a File or URL
pd.read_json() accepts a file path, a URL, or a JSON string directly. For deeply nested JSON (e.g., API responses with nested objects), use json_normalize() from the pandas.io.json module instead, which flattens nested dicts into columns with dot-separated names.
import pandas as pd
from pandas.io.json import json_normalize
# From a file
df = pd.read_json('events.json')
# Flatten nested JSON
nested = [{'id': 1, 'user': {'name': 'A', 'age': 30}},
{'id': 2, 'user': {'name': 'B', 'age': 25}}]
df_flat = json_normalize(nested)
print(df_flat.columns.tolist()) # ['id', 'user.name', 'user.age']JSON Lines Format
JSON Lines (NDJSON) stores one JSON object per line, making it easy to stream large datasets. Use pd.read_json('file.jsonl', lines=True) to parse this format. It is common in log files, Kafka exports, and machine learning dataset formats. Each line must be a valid JSON object; malformed lines cause the read to fail.
import pandas as pd
# file.jsonl contains one JSON record per line:
# {"id": 1, "event": "click"}
# {"id": 2, "event": "view"}
df = pd.read_json('events.jsonl', lines=True)
print(df)Handling Date Parsing in JSON
JSON has no native date type — dates are stored as strings or Unix timestamps (milliseconds or seconds since epoch). Set convert_dates=True (default) to let Pandas attempt auto-conversion of columns whose names contain 'date', 'time', or 'at'. For custom column names or timestamps, convert explicitly with pd.to_datetime(df['col'], unit='ms').
import pandas as pd
# Unix milliseconds timestamp column
df = pd.read_json('events.json', orient='records')
df['created_at'] = pd.to_datetime(df['created_at'], unit='ms')
print(df['created_at'].dtype) # datetime64[ns]Comparing Excel and JSON Gotchas
Excel gotchas: merged cells produce NaN rows, hidden rows/columns are included in the output, and number formatting (e.g., dates stored as floats) must be corrected after loading. JSON gotchas: inconsistent field presence across records produces NaN, and integer keys in a JSON object become string column names.
import pandas as pd
# Excel date stored as float (Excel serial date)
df = pd.read_excel('old_report.xls')
# If dates appear as floats (e.g., 44927.0), convert:
# from xlrd import xldate_as_datetime
# df['date'] = df['date'].apply(lambda x: xldate_as_datetime(x, 0))pd.ExcelFile for Multiple Sheets
When you need to read multiple sheets from the same file efficiently, open a pd.ExcelFile context manager and call parse(sheet_name) for each sheet. This avoids re-opening and re-parsing the file for each sheet — important for large workbooks. The context manager closes the file handle automatically.
import pandas as pd
with pd.ExcelFile('annual_report.xlsx') as xf:
df_q1 = xf.parse('Q1')
df_q2 = xf.parse('Q2')
print(df_q1.shape, df_q2.shape)Using requests to Load JSON APIs
For REST API data, use the requests library to fetch JSON and pass the parsed Python object to pd.DataFrame() or pd.json_normalize(). This pattern separates the HTTP concern from the data parsing concern and gives you access to headers, authentication, and pagination before Pandas touches the data.
import pandas as pd
import requests
response = requests.get('https://api.example.com/records')
data = response.json() # Python list of dicts
df = pd.DataFrame(data)
print(df.head())Quick Check
Test your understanding of reading Excel and JSON files with Pandas from this lesson.
Lesson Recap
In this lesson you learned: pd.read_excel() reads xlsx files and lets you specify which sheet to load via sheet_name, pd.read_json() handles multiple JSON structures controlled by the orient parameter, and json_normalize() flattens nested JSON objects into a flat DataFrame. Next up we export DataFrames to CSV and Excel files for sharing and downstream processing.
자주 묻는 질문
“Excel 및 JSON 파일 읽기” 강의는 무료인가요?
네 — “Excel 및 JSON 파일 읽기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“Excel 및 JSON 파일 읽기”에서 뭘 배우나요?
pd.read_excel로 Excel 통합 문서를, pd.read_json으로 JSON 레코드를 가져오고 일반적인 형식 차이를 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Excel 및 JSON 파일 읽기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- CSV 파일 읽기
- Excel 및 JSON 파일 읽기
- DataFrames를 파일로 쓰기
- URL과 StringIO에서 읽기