파이썬(Python)&판다스(Pandas)&Polars

[Pandas] combine_first - 두 컬럼 중 먼저 나온 값을 기준으로 새로운 컬럼 생성하기

송채채 2022. 10. 24. 17:43

아래 구조와 같이 col1, col2 중 먼저 나오는 데이터를 기준으로 새로운 컬럼을 만들어야하는 경우가 있다.

이때는 'combine_first'를 사용하면 만들 수 있다.

 

 

import pandas as pd 

#둘 중 하나에 값이 있으면 합치기
df['new_col'] = df['col1'].combine_first(df['col2'])
df.drop([['col1','col2]], axis=1, inplace=True) # 필요없는 컬럼은 삭제

 

참고 블로그

- https://wikidocs.net/153673

 

08-02. 다른 객체로 결측치 덮어쓰기 (combine_first)

####DataFrame.combine_first(other) ##개요 `combine_first` 메서드는 `other`의 값으로 `self(df)`의 `NaN`값을 덮 ...

wikidocs.net

 

반응형