Data Science/Pandas

Pandas. apply() 정리 — 함수의 입력과 출력

워로디스 2026. 8. 27. 22:36

1. 입력: 함수에 무엇이 들어오는가

Series.apply()

df["a"].apply(func)

func에는 df["a"]값 하나씩 들어온다.

def func(x):
    # x = 개별 값
    return ...

예:

df["a"].apply(lambda x: x * 2)

a가 다음과 같다면:

10
20
30

함수는 개념적으로 다음처럼 호출된다.

func(10)
func(20)
func(30)

DataFrame.apply(axis=1)

df.apply(func, axis=1)

func에는 행 하나씩 들어온다.

각 행의 타입은 Series이다.

def func(row):
    # row = 한 행 전체
    return ...

예:

df.apply(
    lambda row: row["a"] + row["b"],
    axis=1
)

한 번의 호출에서 row는 대략 다음 형태다.

a    10
b    20
Name: 0
dtype: int64

따라서 여러 컬럼을 함께 사용할 수 있다.

DataFrame.apply(axis=0)

df.apply(func, axis=0)

func에는 열 하나씩 들어온다.

각 열의 타입도 Series이다.

def func(col):
    # col = 한 열 전체
    return ...

axis=0은 기본값이므로:

df.apply(func)

와 같다.

2. 입력 형식 요약

호출 함수가 받는 입력
series.apply(func) 값 하나
df.apply(func, axis=1) 행 하나 (Series)
df.apply(func, axis=0) 열 하나 (Series)

즉:

Series.apply
→ 원소 단위

DataFrame.apply(axis=1)
→ 행 단위

DataFrame.apply(axis=0)
→ 열 단위

x, row, col 같은 이름에는 특별한 의미가 없다.

df.apply(lambda x: x["a"] + x["b"], axis=1)

여기서 x가 행인 이유는 이름이 x라서가 아니라 axis=1이기 때문이다.

3. 출력: 함수가 무엇을 반환하는가

apply()의 결과는 주로 함수의 return에 의해 결정된다.

값 하나를 반환

def func(row):
    return row["a"] + row["b"]

각 호출이 값 하나를 반환하면 결과는 일반적으로 Series다.

result = df.apply(func, axis=1)
0    30
1    50
2    70
dtype: int64

그래서 새 컬럼 하나를 만들 때 흔히 다음 형태를 사용한다.

df["c"] = df.apply(func, axis=1)

Series를 반환

함수가 여러 값을 Series로 반환하면 결과는 DataFrame으로 펼쳐질 수 있다.

def func(row):
    return pd.Series({
        "sum": row["a"] + row["b"],
        "diff": row["a"] - row["b"]
    })

result = df.apply(func, axis=1)

결과:

   sum  diff
0   30   -10
1   50   -10
2   70   -10

즉:

한 행 입력
   ↓
Series 반환
   ↓
여러 행의 Series를 결합
   ↓
DataFrame

4. 가장 자주 사용하는 세 가지 형태

① 한 컬럼의 값을 변환

df["b"] = df["a"].apply(func)
입력: 값 하나
출력: 값 하나

Series → Series

예:

df["b"] = df["a"].apply(lambda x: x * 2)

② 여러 컬럼을 이용해 새 컬럼 하나 생성

df["c"] = df.apply(func, axis=1)
입력: 행 하나
출력: 값 하나

DataFrame → Series

예:

df["c"] = df.apply(
    lambda row: row["a"] + row["b"],
    axis=1
)

③ 여러 컬럼을 이용해 여러 결과 생성

result = df.apply(func, axis=1)
def func(row):
    return pd.Series({
        "c": row["a"] + row["b"],
        "d": row["a"] - row["b"]
    })
입력: 행 하나
출력: Series

DataFrame → DataFrame

5. 정리

코드 함수 입력 함수 반환 일반적인 결과
series.apply(func) 값 하나 값 하나 Series
df.apply(func, axis=1) 행 하나 (Series) 값 하나 Series
df.apply(func, axis=0) 열 하나 (Series) 값 하나 Series
df.apply(func, axis=1) 행 하나 (Series) Series DataFrame

코드를 볼 때 확인하는 순서

1. apply 앞의 객체를 본다.
   Series인가, DataFrame인가?

2. DataFrame이면 axis를 본다.
   axis=1 → 행
   axis=0 → 열

3. 함수의 return을 본다.
   값 하나 → 보통 Series
   Series   → 보통 DataFrame
반응형