데이터프레임의 두 열을 인자로 받는 람다 함수 만들기
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to apply a function to two columns of Pandas dataframe
판다스 데이터프레임의 두 열에 함수를 적용하는 방법
문제 내용
Suppose I have a df
which has columns of 'ID', 'col_1', 'col_2'
. And I define a function :
'ID', 'col_1', 'col_2'의 열이 있는 df가 있다고 가정하자. 그리고 저는 함수를 정의합니다:
f = lambda x, y : my_function_expression
.
f = 람다 x, y : my_function_description.
Now I want to apply the f
to df
's two columns 'col_1', 'col_2'
to element-wise calculate a new column 'col_3'
, somewhat like :
이제 f를 df의 두 열 'col_1', 'col_2'에 적용하여 요소별로 새 열 'col_3'을 계산합니다.
df['col_3'] = df[['col_1','col_2']].apply(f)
# Pandas gives : TypeError: ('<lambda>() takes exactly 2 arguments (1 given)'
How to do ?
어떻게 해요?
** Add detail sample as below ***
** 아래와 같이 세부 샘플 추가 ***
import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
return mylist[sta:end+1]
#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below
ID col_1 col_2 col_3
0 1 0 1 ['a', 'b']
1 2 2 4 ['c', 'd', 'e']
2 3 3 5 ['d', 'e', 'f']
높은 점수를 받은 Solution
There is a clean, one-line way of doing this in Pandas:
판다스는 한 줄로 깔끔하게 처리할 수 있습니다.
df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)
This allows f
to be a user-defined function with multiple input values, and uses (safe) column names rather than (unsafe) numeric indices to access the columns.
이렇게 하면 f가 여러 입력 값을 가진 사용자 정의 함수가 될 수 있으며, (안전하지 않은) 숫자 인덱스 대신 (안전한) 열 이름을 사용하여 열에 액세스할 수 있습니다.
Example with data (based on original question):
데이터가 포함된 예(원문 기반):
import pandas as pd
df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})
mylist = ['a', 'b', 'c', 'd', 'e', 'f']
def get_sublist(sta,end):
return mylist[sta:end+1]
df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)
Output of print(df)
:
print(df)의 출력:
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
If your column names contain spaces or share a name with an existing dataframe attribute, you can index with square brackets:
열 이름에 공백이 포함되어 있거나 기존 데이터 프레임 속성과 이름을 공유하는 경우 대괄호로 인덱싱할 수 있습니다.
df['col_3'] = df.apply(lambda x: f(x['col 1'], x['col 2']), axis=1)
가장 최근 달린 Solution
It can be done in two simple ways: Let's say, we want sum of col1
and col2
in output column named col_sum
두 가지 간단한 방법으로 수행할 수 있습니다. col_sum이라는 출력 열에서 col1과 col2의 합계를 원한다고 가정해 보겠습니다.
- Method 1
방법 1
f = lambda x : x.col1 + x.col2
df['col_sum'] = df.apply(f, axis=1)
- Method 2
방법 2
def f(x):
x['col_sum'] = x.col_1 + col_2
return x
df = df.apply(f, axis=1)
Method 2 should be used when some complex function has to applied to the dataframe. Method 2 can also be used when output in multiple columns is required.
방법 2는 데이터 프레임에 복잡한 기능을 적용해야 할 때 사용해야 합니다. 방법 2는 여러 열의 출력이 필요한 경우에도 사용할 수 있습니다.
출처 : https://stackoverflow.com/questions/13331698/how-to-apply-a-function-to-two-columns-of-pandas-dataframe