NumPy와 Pandas를 바로 시작할 수도 있지만 Python의 기본 문법을 모르면 데이터 분석 코드가 왜 동작하는지 이해하기 어렵다.
특히 다음 개념은 데이터 분석 코드에서 계속 반복해서 등장한다.
이 글에서는 데이터 분석에서 실제로 자주 연결되는 관점으로 Python 기초를 정리한다.
10 + 20
10 - 3
5 * 4
10 / 4
10 // 4
10 % 4
2 ** 10
| 연산자 | 의미 |
|---|---|
+ | 덧셈 |
- | 뺄셈 |
* | 곱셈 |
/ | 나눗셈 |
// | 몫 |
% | 나머지 |
** | 거듭제곱 |
price = 15000
quantity = 3
total = price * quantity
의미가 드러나는 이름을 사용하는 것이 좋다.
conversion_rate = 0.135
sample_size = 1000
0.1 + 0.2
결과는 다음처럼 보일 수 있다.
0.30000000000000004
컴퓨터가 대부분의 실수를 2진 부동소수점으로 표현하기 때문이다.
따라서 다음 비교는 기대와 다를 수 있다.
0.1 + 0.2 == 0.3
허용 오차를 고려하려면:
import math
math.isclose(
0.1 + 0.2,
0.3,
)
평균, 비율, 통계값을 비교할 때 알아두면 좋다.
name = "user-101"
status = "active"
f-string을 사용하면 값과 문자열을 읽기 쉽게 조합할 수 있다.
message = (
f"{name}: {status}"
)
revenue = 1234567.89
print(
f"{revenue:,.0f}원"
)
1,234,568원
비율:
rate = 0.1375
print(
f"{rate:.2%}"
)
13.75%
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
데이터 분류에도 같은 구조를 사용할 수 있다.
amount = 65000
if amount >= 50000:
segment = "high"
else:
segment = "normal"
age >= 20
status == "active"
price != 0
조건 조합:
if (
status == "active"
and amount >= 50000
):
print(
"우선 분석 대상"
)
반복되는 계산에는 함수를 사용한다.
def calculate_rate(
success,
total,
):
if total == 0:
return 0.0
return (
success
/ total
)
rate = calculate_rate(
85,
100,
)
함수로 만들면 계산 로직을 재사용하고 테스트하기 쉬워진다.
def apply_discount(
price,
rate=0.1,
):
return (
price
* (1 - rate)
)
apply_discount(10000)
apply_discount(
10000,
rate=0.2,
)
sales = [
120,
150,
90,
210,
]
인덱싱:
sales[0]
sales[-1]
슬라이싱:
sales[:2]
sales[1:3]
값 추가:
sales.append(180)
for 반복문sales = [
120,
150,
90,
]
for value in sales:
print(value)
합계를 직접 구하면:
total = 0
for value in sales:
total += value
합계만 필요하다면 내장 함수가 더 간단하다.
total = sum(sales)
sales = [
120,
150,
90,
210,
]
high_sales = [
value
for value in sales
if value >= 150
]
[150, 210]
Pandas를 배우기 전 Python 수준에서 필터링 개념을 이해하는 데 도움이 된다.
수정하지 않을 값 묶음에 적합하다.
point = (
37.5,
127.0,
)
언패킹:
latitude, longitude = (
point
)
하나의 데이터 레코드를 표현할 때 유용하다.
user = {
"id": 101,
"age": 29,
"active": True,
}
조회:
user["age"]
키가 없을 수 있다면:
user.get(
"email"
)
users = [
{
"id": 1,
"age": 24,
},
{
"id": 2,
"age": 31,
},
]
for user in users:
print(
user["age"]
)
이런 표 형태의 데이터를 더 강력하게 다루는 도구가 Pandas의 DataFrame이다.
Python에서 문자열, 리스트, 숫자도 모두 객체다.
text = "python"
print(
text.upper()
)
직접 클래스를 만들 수도 있다.
class Metric:
def __init__(
self,
name,
value,
):
self.name = name
self.value = value
def summary(self):
return (
f"{self.name}: "
f"{self.value}"
)
metric = Metric(
"conversion_rate",
0.135,
)
print(
metric.summary()
)
DataFrame, Series, ndarray 같은 라이브러리 객체를 이해할 때 클래스와 메서드 개념이 도움이 된다.
import math
print(
math.sqrt(16)
)
관례적인 별칭:
import numpy as np
import pandas as pd
패키지가 없다면:
python -m pip install numpy pandas
value = 10
print(
type(value)
)
isinstance(
value,
int,
)
변환:
int("10")
float("3.14")
str(100)
from datetime import (
date,
datetime,
timedelta,
)
현재 시간:
now = datetime.now()
날짜 차이:
start = date(
2026,
10,
1,
)
end = date(
2026,
10,
6,
)
diff = end - start
print(
diff.days
)
날짜 더하기:
tomorrow = (
end
+ timedelta(days=1)
)
from datetime import datetime
value = "2026-10-06"
parsed = datetime.strptime(
value,
"%Y-%m-%d",
)
문자열 출력:
parsed.strftime(
"%Y/%m/%d"
)
Pandas 시계열 기능을 이해하기 전에 Python 자체의 날짜와 시간 개념을 익혀두면 좋다.
orders = [
{
"amount": 12000,
"status": "paid",
},
{
"amount": 45000,
"status": "paid",
},
{
"amount": 18000,
"status": "cancelled",
},
]
결제 완료 금액만 합산한다.
total = 0
for order in orders:
if (
order["status"]
!= "paid"
):
continue
total += order["amount"]
print(total)
이 코드에는 데이터 분석에서 계속 사용하는 Python 기초가 들어 있다.
Pandas는 이런 처리 작업을 표 형태 데이터에 맞게 더 편리하게 표현한다.
ndarray, Pandas의 DataFrame도 Python 객체이므로 클래스와 메서드 개념을 이해하면 라이브러리를 배우기 쉬워진다.