• 카테고리

    질문 & 답변
  • 세부 분야

    데이터 분석

  • 해결 여부

    미해결

apply와 assign의 차이점?

21.05.30 16:20 작성 조회수 422

1

apply와 assign이 비슷해보이는데, 차이점이 뭔가요?

답변 1

답변을 작성해보세요.

1

안녕하세요.

apply 와 assign은 둘 다 함수를 사용할 수 있다는 점이 비슷합니다.

apply는 결과를 새로운 컬럼(변수)으로 만들어주려면 결과 값을 다시 데이터프레임에 반영해 주어야 합니다.

assign 은 결과가 데이터 프레임의 변수로 반영이 되도록 합니다.

그래서 apply는 특정 함수를 통해 연산, 전처리를 하고자 할때 사용하며,

assign 은 연산 후 컬럼을 생성하는 역할을 하는데 여러 개의 컬럼을 한번에 생성할 수도 있습니다.

apply 에 대한 pandas 공식 문서의 정의 입니다.

Apply a function along an axis of the DataFrame.

Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument.

apply는 연산결과를 반환하지만 새로운 컬럼으로 생성해 주려면 별도의 처리가 필요합니다.

df.apply(np.sqrt)
     A    B
0  2.0  3.0
1  2.0  3.0
2  2.0  3.0

 assign 에 대한 pandas 공식 문서의 정의 입니다.

Assign new columns to a DataFrame.

Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.

아래 예제를 보면 temp_c라는 컬럼의 연산 결과를 새로운 temp_f 라는 컬럼으로 생성하고 있습니다.

df.assign(temp_f=df['temp_c'] * 9 / 5 + 32)
          temp_c  temp_f
Portland    17.0    62.6
Berkeley    25.0    77.0

증권 데이터로 신호와 소음찾기 강의에 사용한 assign 예제 입니다.

와~~ 빠르고 자세한 답변 너무 감사합니다.

감사합니다 :)